Spring使用注解自动装配 @Autowried
1导入约束
@Autowried用于属性类
- 导入约束:context约束
- 开启注解的支持 context:annotation-config/
<?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"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans
       https://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       https://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!--开启注解的支持-->
    <context:annotation-config/>
    <bean id="cat" class="com.liu.pojo.Cat"></bean>
    <bean id="dog" class="com.liu.pojo.Dog"></bean>
    <!--
    buName  会自动在容器上下文查找,和自己对象set方法后面的值对应的beanID!
    byType  会自动在容器上下文查找,和自己对象属性类型相同的bean!
    -->
    <bean id="people" class="com.liu.pojo.People"></bean>
</beans>
@Autowried
直接在属性上使用即可!也可以在set方式上使用!
使用Autowired 我们可以不用编写Set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合名字byname!
@Nullable  字段标记了这个注解,说明这个字段可以为null
测试代码
public class Peop1e {
//如果显示定义了Autowired的required属性为false,说明这个对象可以为nu11,否则不允许为空@Autowired(required = false)
private cat cat;
@Autowired
private Dog dog;
private string name;
如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成的时候、我们可以使用@Qualifier(value="xxx")去配置@Autowired的使用,指定一个唯一的bean对象注入!
    <bean id="cat0" class="com.liu.pojo.Cat"></bean>
    <bean id="cat1" class="com.liu.pojo.Cat"></bean>
    @Autowired
    @Qualifier(value = "cat1")
    private Cat cat;
    @resource(value = "dog1")
    private Dog dog;
@Resource和@Autowired的区别:
- 都是用来自动装配的,都可以放在属性字段上
- @Autowired通过byType的方式实现,而且必须要求这个对象存在!【常用】
- @Resource默认通过byname的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
- 执行顺序不同:@Autowired通过byType的方式实现。@Resource默认通过byname的方式实现。
 
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号