Spring入门(四)——Bean的自动装配

7、Bean的自动装配

  • 自动装配是spring满足bean依赖的一种方式!
  • Spring会在上下文中自动寻找,并自动给bean装配属性!

在Spring中由三种装配方式:

  1. 在xml中显示的配置
  2. 在Java中显示配置
  3. 隐式的自动配置bean【重点】

7.1、测试

  1. 搭建环境

  2. 新建两个实体类,cat,dog

    public class Cat {
       public void shout() {
           System.out.println("miao~");
      }
    }
    
    public class Dog {
       public void shout() {
           System.out.println("wang~");
      }
    }
    
  3. 新建一个用户类

    package com.ysl.pojo;
    
    public class People {
        private cat cat;
        private dog dog;
        private String name;
    
        public com.ysl.pojo.cat getCat() {
            return cat;
        }
    
        public void setCat(com.ysl.pojo.cat cat) {
            this.cat = cat;
        }
    
        public com.ysl.pojo.dog getDog() {
            return dog;
        }
    
        public void setDog(com.ysl.pojo.dog dog) {
            this.dog = dog;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            return "People{" +
                    "cat=" + cat +
                    ", dog=" + dog +
                    ", name='" + name + '\'' +
                    '}';
        }
    }
    
    
  4. 编写beans.xml文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
       <bean id="dog" class="com.kuang.pojo.Dog"/>
       <bean id="cat" class="com.kuang.pojo.Cat"/>
    
       <bean id="user" class="com.kuang.pojo.User">
           <property name="cat" ref="cat"/>
           <property name="dog" ref="dog"/>
           <property name="str" value="qinjiang"/>
       </bean>
    </beans>
    
  5. 测试

    @Test
        public void test01(){
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            People ysl = context.getBean("ysl", People.class);
            ysl.getCat().shout();
            ysl.getDog().shout();
        }
    

7.2、ByName自动装配

byName

autowire byName (按名称自动装配)

由于在手动配置xml过程中,常常发生字母缺漏和大小写等错误,而无法对其进行检查,使得开发效率降低。

采用自动装配将避免这些错误,并且使配置简单化。

测试:

  1. 修改bean配置,增加一个属性 autowire = “byName”

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
       <bean id="dog" class="com.kuang.pojo.Dog"/>
       <bean id="cat" class="com.kuang.pojo.Cat"/>
    
       <bean id="user" class="com.kuang.pojo.User" autowire="byName">
           <property name="str" value="qinjiang"/>
       </bean>
    </beans>
    
  2. 再次测试,结果依旧成功输出!

  3. 我们将 cat 的bean id修改为 catXXX

  4. 再次测试, 执行时报空指针java.lang.NullPointerException。因为按byName规则找不对应set方法,真正的setCat就没执行,对象就没有初始化,所以调用时就会报空指针错误。

小结:

当一个bean节点带有 autowire byName的属性时。

  1. 将查找其类中所有的set方法名,例如setCat,获得将set去掉并且首字母小写的字符串,即cat。
  2. 去spring容器中寻找是否有此字符串名称id的对象。
  3. 如果有,就取出注入;如果没有,就报空指针异常。

7.3、ByType自动装配

byType

autowire byType (按类型自动装配)

使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。

NoUniqueBeanDefinitionException

测试:

1、将user的bean配置修改一下 : autowire=“byType”

2、测试,正常输出

3、在注册一个cat 的bean对象!

<bean id="dog" class="com.kuang.pojo.Dog"/>
<bean id="cat" class="com.kuang.pojo.Cat"/>
<bean id="cat2" class="com.kuang.pojo.Cat"/>

<bean id="user" class="com.kuang.pojo.User" autowire="byType">
   <property name="str" value="qinjiang"/>
</bean>

4、测试,报错:NoUniqueBeanDefinitionException

5、删掉cat2,将cat的bean名称改掉!测试!因为是按类型装配,所以并不会报异常,也不影响最后的结果。甚至将id属性去掉,也不影响结果。

这就是按照类型自动装配!

小结:

  • byName的时候,需要保证所有的bean的id唯一,并且这个bean需要和自动注入的属性的set方法的值一致!
  • byType的时候,需要保证所有的bean的class唯一,并且这个bean需要和自动注入的属性的类型一致!

7.4、使用注解实现自动装配

jdk1.5的支持注解,Spring2.5就支持注解了!

The introduction of annotation-based configuration raised the question of whether this approach is “better” than XML.

要使用注解须知:

  1. 导入约束。context约束

  2. 配置注解的支持: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"
        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">
    
        <context:annotation-config/>
    
    </beans>
    

@Autowired

直接在属性上使用即可!也可以在set方法上使用!

使用Autwired我们可以不用编写set方法了,前提是你这个自动装配的属性在IOC(Spring)容器中存在,且符合byName规范!

科普:

@Nullable  字段标记了这个注解,说明这个字段可以为null
public @interface Autowired {
    boolean required() default true;
}
public class People {
    //如果显示的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired
    private cat cat;
    @Autowired
    private dog dog;
    private String name;
}

如果@Autowired自动装配的环境比较复杂,自动装配无法通过一个注解【@Autowired】完成时,我们可以使用@Qualifier(value = “xxx”)取配置@Autowired的使用,指定一个唯一的bean对象注入!

public class People {
    //如果显示的定义了Autowired的required属性为false,说明这个对象可以为null,否则不允许为空
    @Autowired
    @Qualifier(value = "cat11")
    private cat cat;

    @Autowired
    @Qualifier(value = "dog22")
    private dog dog;
    private String name;
}

@Resource注解

public class People {

    @Resource(name = "cat1")
    private cat cat;
    @Resource
    private dog dog;
    private String name;
}

小结:

@Resource和@Autowired区别:

  • 都是用来自动装配的,都可以放在属性字段上!
  • @Autowired默认通过byType的方式实现,而且必须要求这个对象存在!【常用】
  • @Resource默认通过byName的方式实现,如果找不到名字,则通过byType实现!如果两个都找不到的情况下,就报错!【常用】
  • @Resource是jdk提供的注解,它默认使用byName进行装配,byName无法装配则使用byType;
  • @Autowired是spring提供的注解,@Autowired默认使用byType进行装配,byType无法装配则使用byName,如果接口有多个实现类,需要配合@Qualifier注解使用。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值