自动装配
手动实现
<bean id="cat" class="com.chao.pojo.Cat"/>
<bean id="dog" class="com.chao.pojo.Dog"/>
<!--
byName:会自动在容器上下文中查找。和自己对象set方法后面的值对应的beanid!
byType:会自动在容器上下文中查找,利自己对象属性类型!相同的bean!
-->
<bean id="person" class="com.chao.pojo.Person" autowire="byName">
<property name="name" value="吴梓超" />
</bean>
<bean id="person1" class="com.chao.pojo.Person" autowire="byType">
<property name="name" value="吴梓超" />
</bean>
注解实现
1、在spring配置文件中引入context文件头和约束
2、开启属性注解支持!context:annotation-config/
配置好context:annotation-config/IDEA会自动导入头文件需要的约束信息
@Autowired
@Autowired注入首先根据byType注入,当类型大于1时在根据byName注入。
如果显示定义@Autowired的required属性为false,说明这个对象可以为null.否则不允许为空,等同于@Nullable
@Autowired(required = false)
实例:
@Getter
@Setter
@ToString
public class Person {
@Autowired
private Cat cat;
@Autowired
private Dog dog;
private String name;
}
<?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
https://www.springframework.org/schema/context/spring-context.xsd">
<context:annotation-config/>
<bean id="cat" class="com.chao.pojo.Cat"/>
<bean id="dog" class="com.chao.pojo.Dog"/>
<bean id="person" class="com.chao.pojo.Person"/>
</beans>
@Test
public void test1(){
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
Person person = context.getBean("person", Person.class);
person.getCat().shout();
person.getDog().shout();
}
@Qualifier
@Autowired一般与@Qualifier(value = "xxx")配合使用,@Qualifier不能单独使用。
@Autowired
@Qualifier(value = "cat11")
测试实验步骤:
1、配置文件修改内容,保证类型存在对象。且名字不为类的默认名字!
<bean id="dog1" class="com.kuang.pojo.Dog"/>
<bean id="dog2" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
2、没有加Qualifier测试,直接报错
3、在属性上添加Qualifier注解
@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;
测试,成功输出!
@Resource
- @Resource如有指定的name属性,先按该属性进行byName方式查找装配;
- 其次再进行默认的byName方式进行装配;
- 如果以上都不成功,则按byType的方式自动装配。
- 都不成功,则报异常。
实体类:
public class User {
//如果允许对象为null,设置required = false,默认为true
@Resource(name = "cat2")
private Cat cat;
@Resource
private Dog dog;
private String str;
}
beans.xml
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>
<bean id="user" class="com.kuang.pojo.User"/>
测试:结果OK
配置文件2:beans.xml , 删掉cat2
<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat1" class="com.kuang.pojo.Cat"/>
实体类上只保留注解
@Resource
private Cat cat;
@Resource
private Dog dog;
结果:OK
结论:先进行byName查找,失败;再进行byType查找,成功。