一、@Autowired
先来一个简单的实现类,和xml配置文件
public class Person {
private String name;
private Cat cat;
private Dog dog;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="cat" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>
<bean id="people" class="com.wang.pojo.Person">
<property name="name" value="小王"/>
</bean>
</beans>
1.可见在xml配置文件中,cat和dog 的bean都只有一个,可直接在实现类属性上添加注解@Autowired,不需要编写set方法,实现自动装配
public class Person {
private String name;
@Autowired
private Cat cat;
@Autowired
private Dog dog;
}
2.如果当xml配置文件中,出现多个cat的bean时,我们需要怎么解决?
<bean id="cat" class="com.wang.pojo.Cat"/>
<bean id="cat2" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>
@Autowired默认的自动装配方式为byType,通过类型装配,但是现在有了两个cat bean,它会byName来实现装配,那么name之间是怎么对应的呢?
bean的id 与 类中具体的属性名相对应,即 bean id=“cat” class=“com.wang.pojo.Cat” 中的 id = cat与 private Cat cat 中 cat 相一致时,即可实现自动装配
3.如果当xml配置文件中,id 与 属性名 都不一致时,怎么解决?
<bean id="cat1" class="com.wang.pojo.Cat"/>
<bean id="cat2" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>
可以@Autowired与@Qualifier注解并用来解决
public class Person {
private String name;
@Autowired
@Qualifier(value="cat1") // 其中的value值要对应bean中的id值即可
private Cat cat;
@Autowired
private Dog dog;
}
二、@Resource
1.当xml文件中只有一个对应cat的bean时,不论id名与属性名相同与否,都会实现自动装配
public class Person {
private String name;
@Resource
private Cat cat;
@Autowired
private Dog dog;
}
2.但是当xml文件中有多个cat对应的bean时
<bean id="cat" class="com.wang.pojo.Cat"/>
<bean id="cat2" class="com.wang.pojo.Cat"/>
<bean id="dog" class="com.wang.pojo.Dog"/>
此时,我们只需标注@Resource,并保证id与属性名一致才能实现自动装配
public class Person {
private String name;
@Resource
private Cat cat;
@Autowired
private Dog dog;
}
相比于@Autowired,@Resource更强大一些