Spring基于注解注入bean(十四)

1.@Autowired注解是通过匹配数据类型自动装配Bean

在属性的的上面或者构造方法或者setter方法上面加上@Autowired会通过byType按照类型注入。

需要使用@Autowired,需要配置文件启动注解,使注解生效:

<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>

或者

<context:annotation-config />

@Autowired有如下使用情况:

	//setter
	@Autowired
	public void setPerson(Person person) {
		this.person = person;
	}
	//构造
	@Autowired
	public Customer(Person person) {
		this.person = person;
	}
	//属性
	@Autowired
	private Person person;

使用@Autowired注解默认会进行依赖检查,当配置上下问中不存在这种类型的bean会抛出异常,可以通过设置不进行依赖检查,如下:

@Autowired(required=false)

当配置上下文中存在两个同样类型的bean,@Autowired是按照type注入会抛出异常,可以通过@Quanlifier指明注入那个bean,如下:

	@Autowired
	@Qualifier("personA")
	private Person person;

2.@Resource注解

@Resource注解与@Autowired使用方法大致相同,

1、@Resource后面没有任何内容,默认通过name属性去匹配bean,找不到再按type去匹配
2、指定了name或者type则根据指定的类型去匹配bean
3、指定了name和type则根据指定的name和type去匹配bean,任何一个不匹配都将报错

然后,区分一下@Autowired和@Resource两个注解的区别:
1、@Autowired默认按照byType方式进行bean匹配,@Resource默认按照byName方式进行bean匹配
2、@Autowired是Spring的注解,@Resource是J2EE的注解,这个看一下导入注解的时候这两个注解的包名就一清二楚了

注:Spring属于第三方的,J2EE是Java自己的东西,因此,建议使用@Resource注解,以减少代码和Spring之间的耦合。

猜你喜欢

转载自blog.csdn.net/qq_36831305/article/details/89365487