Spring注解注入集合对象

目录

1. @Autowired注解注入map、list与@Qualifier

2. Spring依赖注入IoC各种数据类型(list、map、set、数组)


1. @Autowired注解注入map、list与@Qualifier

package com.imooc.beanannotation.multibean;

public interface BeanInterface {
}
package com.imooc.beanannotation.multibean;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @order 注解可以调整注入顺序,但只对list有效,对map无效。 
 *
 */
@Order(2)
@Component
public class BeanImplOne implements BeanInterface {
}
package com.imooc.beanannotation.multibean;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(1)
@Component
public class BeanImplTwo implements BeanInterface {
}
package com.imooc.beanannotation.multibean;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class BeanInvoker {

    @Autowired
    private List<BeanInterface> list;

    /**
     * 对于向map中注入,bean注入后string为该bean的id。
    */
    @Autowired
    private Map<String, BeanInterface> map;

    /** @Autowired默认为by Type的  所以有两个相同类型的bean  
     * 如果不使用 @Qualifier指定具体的bean就会抛出异常
    */
    @Autowired
    @Qualifier("beanImplTwo")
    private BeanInterface beanInterface;

    public void say() {
        if (null != list && 0 != list.size()) {
            System.out.println("list...");
            for (BeanInterface bean : list) {
                System.out.println(bean.getClass().getName());
            }
        } else {
            System.out.println("List<BeanInterface> list is null !!!!!!!!!!");
        }

        System.out.println();

        if (null != map && 0 != map.size()) {
            System.out.println("map...");
            for (Map.Entry<String, BeanInterface> entry : map.entrySet()) {
                System.out.println(entry.getKey() + "      " + entry.getValue().getClass().getName());
            }
        } else {
            System.out.println("Map<String, BeanInterface> map is null !!!!!!!!!!");
        }

        System.out.println();
        if (null != beanInterface) {
            System.out.println(beanInterface.getClass().getName());
        } else {
            System.out.println("beanInterface is null...");
        }
    }
}

配置文件:

<?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:component-scan base-package="package com.imooc.beanannotation.multibean;"> 
    </context:component-scan>        
</beans>

测试类:

package com.Autowired.ListMap;
 
import org.junit.Test;
 
import com.imooc.test.base.UnitTestBase;
 
 
public class TestListMap  extends UnitTestBase{
    public TestListMap(){
    	super("classpath*:spring-beanannotation3.xml");
    }
    
    @Test
    public void test(){
    	BeanInvoke  bean=super.getBean("beanInvoke");
    	bean.say();
    }
}

结果:

2017-6-4 15:38:26 org.springframework.context.support.AbstractApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@58a17083: startup date [Sun Jun 04 15:38:26 CST 2017]; root of context hierarchy
2017-6-4 15:38:26 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
信息: Loading XML bean definitions from URL [file:/E:/myeclipse/workspace/Spring2/bin/spring-beanannotation3.xml]
2017-6-4 15:38:27 org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init>
信息: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
list...
2017-6-4 15:38:27 org.springframework.context.support.AbstractApplicationContext doClose
信息: Closing org.springframework.context.support.ClassPathXmlApplicationContext@58a17083: startup date [Sun Jun 04 15:38:26 CST 2017]; root of context hierarchy
com.Autowired.ListMap.BeanImplTwo
com.Autowired.ListMap.BeanImplOne
 
map...
beanImplOne    com.Autowired.ListMap.BeanImplOne
beanImplTwo    com.Autowired.ListMap.BeanImplTwo
-------------------------
com.Autowired.ListMap.BeanImplOne

以上是示例demo。当时看到这里之后有些懵,全局搜索之后并没有发现定义一个List和Map的对象。然而debug运行之后却发现它们的确都有值。觉得很奇怪,最后在调试List的时候突然灵感一闪,如果只有一个对象那么List里面的值不就只有一个吗。于是开始测试验证,结果发现的确如此。当实例化一个BeanInterface之后,另外一个类采用泛型注入List,Spring竟然成功的将实例化的对象放入List之中。思路打开之后,针对Map的就更好说了。Spring会将service的名字作为key,对象作为value封装进入Map。

2. Spring依赖注入IoC各种数据类型(list、map、set、数组)

public class TestEntity {
    private List<String> list; // List类型
    private String[] array; // 数组类型
    private Set<String> set; // Set类型
    private Map<String, String> map; // Map类型

    //为属性添加set方法省略

    public void showValue() {
    System.out.println("List属性:" + this.list);
    System.out.println("数组属性[0]:" + this.array[0]);
    System.out.println("Set属性:" + this.set);
    System.out.println("Map属性:" + this.map);
    }
}

配置文件:(有一点需要注意:标签中的name属性值,必须和注入实体类中的属性相同。)

<!-- 注入List类型 -->
    <property name="list">
        <list>
            <!-- 定义List中的元素 -->
            <!-- 直接用value标签为list赋值 -->
            <value>足球</value>
            <value>篮球</value>
        </list>
    </property>
    <!-- 注入数组类型 -->
    <property name="array">
        <list>
            <!-- 定义数组中的元素 -->
            <value>足球</value>
            <value>篮球</value>
        </list>
    </property>
    <!-- 注入Set类型 -->
    <property name="set">
        <list>
            <!-- 定义Set中的元素 -->
            <value>足球</value>
            <value>篮球</value>
        </list>
    </property>
    <!--↑ list、数组和set集合很像爱那个,赋值的方法没有区别 ↑ -->

    <!-- 注入Map类型 -->
    <property name="map">
        <map>
            <!-- 定义Map中的键值对 -->
            <entry>
                <key>
                    <value>football</value>
                </key>
                <!-- ↑map集合中的键↑ -->
                <!-- 上下分别为键-值对应 -->
                <!-- ↓map集合中的键↓ -->
                <value>足球</value>
            </entry>
            <entry>
                <key>
                    <value>basketball</value>
                </key>
                <value>篮球</value>
            </entry>
        </map>
    </property>

运行结果如下:

List属性:[足球, 篮球]
数组属性[0]:足球
Set属性:[足球, 篮球]
Map属性:{football=足球, basketball=篮球}

此外还有为类中的属性注入Properties属性、注入空字符串、注入null值,在这里简要地说明一下:

像其他的类型一样,定义属性并添加set()方法、添加打印代码,便于我们观察:

private Properties props; // Properties类型
private String emptyValue; // 注入空字符串值
private String nullValue = "init value"; // 注入null值

System.out.println("Properties属性:" + this.props);
System.out.println("注入空字符串:[" + this.emptyValue + "]");
System.out.println("注入null值:" + this.nullValue);

做完这些工作以后,配置applicationContext.xml配置文件:

<!-- 注入Properties类型 -->
    <property name="props">
        <props>
            <!-- 定义Properties中的键值对 -->
            <prop key="football">足球</prop>
            <prop key="basketball">篮球</prop>
        </props>
    </property>
    <!-- 注入空字符串值 -->
    <property name="emptyValue">
        <!-- value标签之前什么也不写,即为空字符串 -->
        <value></value>
    </property>
    <!-- 注入null值 -->
    <property name="nullValue">
        <!-- null标签 -->
        <null />
    </property>

这篇文章了。

猜你喜欢

转载自blog.csdn.net/huanghanqian/article/details/81835590
今日推荐