这些简单的Spring Bean注入方式,你都会吗?

1,107 阅读1分钟

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