共计 2380 个字符,预计需要花费 6 分钟才能阅读完成。
Spring 注入 bean 的形式
- 注解注入
案例实操
注解形式注入
对于 bean 的注入,除了应用 xml 配置以外,注解的配置简化开发的速度,使程序看上去更加简洁。对于注解的解释,spring 对于注解有专门的解释器,对定义的注解进行解析,实现对应 bean 对象的注入, 反射技术实现。
1. 退出 spring-aop jar 包 spring-aop-4.3.2.RELEASE.jar
2.Xml 配置:退出 context 命名空间和 xsd 地址
3. 增加 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 | |
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/> | |
<bean id="userDao" class="com.xxx.demo.UserDao"></bean> | |
<bean id="userService" class="com.xxx.demo.UserService"></bean> | |
</beans> |
对于 bean 的注入罕用注解类型
@Autowired 属性字段或 set 办法上
@Resource 属性字段或 set 办法上
区别:@Autowired 默认按 bean 的类型匹配能够批改按名称匹配和 @Qualifier 配合应用 @Resource 默认按名称进行拆卸,名称能够通过 name 属性进行指定,如果没有指定 name 属性,当注解写在字段上时,默认取字段名进行匹配注入,如果注解写在 setter 办法上默认取属性名进行拆卸。当找不到与名称匹配的 bean 时才依照类型进行拆卸。然而须要留神的是,如果 name 属性一旦指定,就只会依照名称进行拆卸。
举荐应用 @Resource 注解是属于 J2EE 的,缩小了与 spring 的耦合。
扩大
IoC 汇合类型属性注入
list 汇合注入
<bean id="listDI" class="com.xxx.demo.ListDI"> | |
<property name="list"> | |
<list> | |
<value> 河南烩面 </value> | |
<value> 北方臊子面 </value> | |
<value> 油泼面 </value> | |
<value> 方便面 </value> | |
</list> | |
</property> | |
</bean> |
set 汇合注入
<bean id="listDI" class="com.xxx.demo.ListDI"> | |
<property name="set"> | |
<set> | |
<value> 高兴小馒头 </value> | |
<value> 南方大馒头 </value> | |
<value> 天津麻花 </value> | |
<value> 新疆大饼 </value> | |
</set> | |
</property> | |
</bean> |
map 类型属性注入
<bean id="userServiceImpl"class="com.xxx.demo.ListDI"> | |
<property name="map"> | |
<map> | |
<entry> | |
<key><value> 河南 </value></key> | |
<value> 云台山风光 </value> | |
</entry> | |
<entry> | |
<key><value> 上海 </value></key> | |
<value> 宝塔 </value> | |
</entry> | |
<entry> | |
<key><value> 北京 </value></key> | |
<value> 紫禁城 </value> | |
</entry> | |
</map> | |
</property> | |
</bean> |
for(Map.Entry<String,Object> entry:map.entrySet()){System.out.println("key:"+entry.getKey()+":value"+entry.getValue()); | |
} |
properties 属性注入
<bean id="userServiceImpl" class="com.xxx.demo.ListDI"> | |
<property name="prop"> | |
<props> | |
<prop key="北京"> 长城 </prop> | |
<prop key="上海"> 东方明珠 </prop> | |
<prop key="西安"> 兵马俑 </prop> | |
</props> | |
</property> | |
</bean> |
public void printProperties(){Set<Map.Entry<Object,Object>> set=properties.entrySet(); | |
Iterator<Map.Entry<Object,Object>> iterator=set.iterator; | |
while(iterator.hasNext()){Map.Entry<Object,Object> entry=iterator.next(); | |
System.out.println(entry.getKey()+"...."+entry.getValue()) | |
} | |
} |
正文完