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())    }}