Autowiring a bean with list of values in a propert

2019-07-20 00:58发布

问题:

My Xml file:

  <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="filterBySlic" class="ca.ups.tundra.msg.FilterMessagesBySlic">
        <property name="slicList">
            <list><value>4196</value><value>1101</value><value>2795</value></list>
        </property>
        <property name="messageList">
            <list><value>7762</value><value>7765</value><value>7766</value><value>7767</value><value>7768</value></list>
        </property>
        <property name="serviceLevelList">
            <list><value>E1</value><value>E3</value><value>E4</value><value>29</value></list>
        </property>
        <property name="serviceTypeList">
            <list><value>029</value><value>096</value></list>
        </property>
    </bean>

</beans>

this is what I am using in my class:

ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"spring-pred-filter.xml"});

FilterMessagesBySlic filterConfig = (FilterMessagesBySlic)context.getBean("filterBySlic");

my condition to access the list of values;

filterConfig.getSiteList().contains(msgSlic)

which is working fine. Instead I need to use @Autowired to access those list of values! Any suggestion

回答1:

you can change your lists from being anonymous inner beans to normal beans and inject them in other beans like this:

xml configuration:

<util:list id="slicList" value-type="java.lang.String">
    <value>4196</value>
    <value>1101</value>
    <value>2795</value>
</util:list>

injecting slicList in a bean:

public class Foo {
    @Resource(name = "slicList")
    List<String> messageList;
}

this implies of course that the instance of Foo is managed by spring.

is it what you are looking for?