Spring中bean有三种装配方式:
1.在xml文件中显式配置。(前面介绍IOC和DI的博客已经详细介绍了)
2.在Java中显式配置。
3.隐式的bean自动装配。(本篇博客重点)
bean自动装配方式:
一、byName方式
修改bean配置,增加一个属性 autowire=“byName”
<bean id="cs" class="com.CS"/>
<bean id="lol" class="com.LOL"/>
<bean id="student" class="com.Student" autowire="byName">
</bean>
注意点:首先,将查找其类中所有的set方法名,例如setlol,获得将set去掉并且首字母小写的字符串,即lol。去spring容器中寻找是否有此字符串名称id的对象。如果有,就取出注入;如果没有,就报空指针异常。
二、byType方式
修改bean配置,增加一个属性 autowire=“byType”
<bean id="cs" class="com.CS"/>
<bean id="lol" class="com.LOL"/>
<bean id="student" class="com.Student" autowire="byType">
</bean>
注意:使用autowire byType首先需要保证:同一类型的对象,在spring容器中唯一。如果不唯一,会报不唯一的异常。
三、使用注解(重点)
其实上面两种方式几乎用不到,但是,其实注解底层也是调用上面两种方式来自动装配的。
XML中需要添加的配置:
1、在spring配置文件中引入context文件头
xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
2、开启属性注解支持!
<context:annotation-config/>
来个总结版的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"
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/>
@Autowired
@Autowired是按类型自动转配的,默认先类型,其次是id,即先byType再byName。
示例代码:
@Autowired
private CS cs;
@Autowired
private LOL lol;
<bean id="cs" class="com.CS"/>
<bean id="lol" class="com.LOL"/>
网上有人说,@Autowired是按类型,不能按照id,但是本人亲测,就上面的代码和配置,当类型重复时,仍然可以按照id装配成功,但是,如果类型和id都不匹配,就真的不行了。
本人亲自测试:CS类型重复了,但是cs对象仍然可以根据id自动装配出来,没有报错。测试代码如下:
<bean id="cs123" class="com.CS"/>
<bean id="cs" class="com.CS"/>
<bean id="lol" class="com.LOL"/>
补充:
@Autowired(required=false)
说明:false,对象可以为null;true,对象必须存对象,不能为null。
@Qualifier
说明:可以添加@Qualifier,然后在value处更改后,byName就可以按照value来找到bean(之前只能默认根据id)
@Autowired
@Qualifier(value = "cs123")
private CS cs;
@Resource
@Resource和@Autowired的区别:
1.@Autowired是spring包中的,@Resource是Java包中的。
2.@Autowired是先按类型,再按byName。@Resource正好相反,是先按照byName,再按照类型。
3.其实他俩功能差不多,都能实现根据注解自动装配,使用方式也一样,都可以写在属性上或者set方法上。