文章目录
基本数据类型和String
示例:
<bean id="user" class="com.harvey.service.impl.UserImpl">
<constructor-arg name="name" value="test"></constructor-arg>
<constructor-arg name="age" value="18"></constructor-arg>
</bean>
使用的标签:constructor-arg
标签出现的位置:bean标签的内部
constructor-arg标签的属性
属性 | 作用 |
---|---|
type | 用于指定要注入的数据的数据类型,该数据类型也是构造函数中某个或某些参数的类型 |
index | 用于指定要注入的数据给构造函数中指定索引位置的参数赋值。索引的位置是从0开始 |
name | 用于指定给构造函数中指定名称的参数赋值 常用 |
value | 用于提供基本类型和String类型的数据 |
ref | 用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象 |
示例:
<bean id="user" class="com.harvey.service.impl.UserImpl">
<property name="name" value="TEST" ></property>
<property name="age" value="81"></property>
</bean>
使用的标签:property
出现的位置:bean标签的内部
property标签的属性
属性 | 作用 |
---|---|
name | 用于指定注入时所调用的set方法名称 |
value | 用于提供基本类型和String类型的数据 |
ref | 用于指定其他的bean类型数据。它指的就是在spring的Ioc核心容器中出现过的bean对象 |
示例:
@Repository("user")
public class User {
@Value("test")
private String name;
@Value("18")
private int age;
}
Value注解用于注入基本类型和String类型的数据,value属性用于指定数据的值。它可以使用spring中SpEL(也就是spring的el表达式)
SpEL的写法:${表达式}
其他bean类型(在配置文件中或者注解配置过的bean)
示例:
<bean id="user" class="com.harvey.service.impl.UserImpl">
<constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>
示例:
<bean id="user" class="com.harvey.service.impl.UserImpl">
<property name="birthday" ref="now"></property>
</bean>
<!-- 配置一个日期对象 -->
<bean id="now" class="java.util.Date"></bean>
注解实现属性依赖注入,将注解加在setXxx方法上 或者 属性定义上 !(任选其一,省代码了)依赖注入 dao
- 使用@Value 结合SpEL #{}
@Va1ue("#{userDao}")
private UserDao userDao;
- 使用@Autowired 结合 @Qualifier
单独使用@Autowired 按照类型注入
@Autowired
private UserDao userDao;
使用@Autowired + @ Qualifier 按照名称注入
@Autowired
@Qualifier(”userDao")
private UserDao userDao;
@Autowired,自动按照类型注入。只要容器中有唯一的一个bean对象类型和要注入的变量类型匹配,就可以注入成功;如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错;如果Ioc容器中有多个类型匹配时,需要配合Qualifier注解使用。可以放在变量上,也可以放在方法上。 在使用注解注入时,set方法就不是必须的了
@Qualifier,在按照类中注入的基础之上再按照名称注入。它在给类成员注入时不能单独使用。但是在给方法参数注入时可以单独使用,value属性用于指定注入bean的id
- 使用@Resource
@Resource(name= "userDao")
private UserDao userDao;
@Resource,直接按照bean的id注入,它可以独立使用。name属性用于指定bean的id
复杂类型/集合类型
示例:
<bean id="user" class="com.harvey.service.impl.UserImpl">
<property name="myStrs">
<set>
<value>AAA</value>
<value>BBB</value>
<value>CCC</value>
</set>
</property>
<property name="myMap">
<props>
<prop key="testC">ccc</prop>
<prop key="testD">ddd</prop>
</props>
</property>
<property name="myProps">
<map>
<entry key="testA" value="aaa"></entry>
<entry key="testB">
<value>BBB</value>
</entry>
</map>
</property>
</bean>
用于给List结构集合注入的标签有: list array set
用于个Map结构集合注入的标签有: map props
结构相同,标签可以互换
集合类型的注入只能通过XML配置来实现
三种注入方式的优缺点
名称 | 优点 | 缺点 |
---|---|---|
构造函数注入 | 在获取bean对象时,注入数据是必须的操作,否则对象无法创建成功 | 改变了bean对象的实例化方式,使我们在创建对象时,如果用不到这些数据,也必须提供 |
set方法注入 | 创建对象时没有明确的限制,可以直接使用默认构造函数 | 如果有某个成员必须有值,则获取对象是有可能set方法没有执行 |
注解注入 | 精短,可读性高,不需要多余的代码,也方便维护 | 不推荐,因为它的弊端确实远大于这些优点 |
三种方式具体的优缺点请看这篇文章
Spring注解依赖注入的三种方式的优缺点以及优先选择