使用注解配置spring如@Compnent、@Service、@Consroller、@scope和@value的使用

步骤

1.导包4+2+spring-aop

如图:为学习到该阶段需要用到的包(里面的aop+test是spring和junit整合测试的时候用到的)

2.为主配置文件引入新的命名空间(约束)




3.开启使用注解代理配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd ">

<!-- 指定扫描cn.itcast.bean报下的所有类中的注解.
	 注意:扫描包时.会扫描指定报下的所有子孙包
 -->
<context:component-scan base-package="cn.itcast.bean"></context:component-scan>

</beans>

在类中使用注解完成配置

  1. 将对象注册到容器
@Component("user")
	@Service("user") // service层
	@Controller("user") // web层
他们三个只是名字不同都实现了把user添加到组件中,区别只是通过名称可以知道该逻辑是在哪一个层次中

2.修改对象的作用范围

@Scope(scopeName="singleton|prototype"


3.值类型注入

在声明是变量前面注入内容
	@Value("18")
	private Integer age;

通过反射的Field赋值,破坏了封装性
在声明set方法前注入内容
	@Value("玛莎拉蒂")
	public void setName(String name) {
		this.name = name;
	}


4.引用类型注入

	@Autowired
	private Car car;
自动装配
问题:如果匹配多个类型一致的对象.将无法选择具体注入哪一个对象.
@Qualifier("car2")//使用@Qualifier注解告诉spring容器自动装配哪个名称的对象
手动装配
@Resource(name="car")//手动注入,指定注入哪个名称的对象

5.初始化|销毁方法

	@PostConstruct //在对象被创建后调用.init-method
	public void init(){
		System.out.println("我是初始化方法!");
	}
	@PreDestroy //在销毁之前调用.destory-method
	public void destory(){
		System.out.println("我是销毁方法!");
	}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值