reading a dynamic property list into a spring managed bean

后端 未结 5 1596
醉梦人生
醉梦人生 2020-12-02 20:38

I\'ve been searching but cannot find these steps. I hope I\'m missing something obvious.

I have a properties file with the following contents:

machin         


        
相关标签:
5条回答
  • 2020-12-02 21:04

    If you make the property "machines" a String array, then spring will do it automatically for you

    machines=B,C,D
    
    <property name="machines" value="${machines}"/>
    
    public void setMachines(String[] test) {
    
    0 讨论(0)
  • 2020-12-02 21:13

    You can inject the values to the list directly without boilerplate code.(Spring 3.1+)

    @Value("${machines}")
    private List<String> machines;
    

    for the key "machines=B,C,D" in the properties file by creating following two instance in your configuration.

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }
    
    @Bean 
    public ConversionService conversionService() {
        return new DefaultConversionService();
    }
    

    Those will cover all the separate based split and whitespace trim as well.

    0 讨论(0)
  • 2020-12-02 21:14

    You may want to take a look at Spring's StringUtils class. It has a number of useful methods to convert a comma separated list to a Set or a String array. You can use any of these utility methods, using Spring's factory-method framework, to inject a parsed value into your bean. Here is an example:

    <property name="machines">
        <bean class="org.springframework.util.StringUtils" factory-method="commaDelimitedListToSet">
            <constructor-arg type="java.lang.String" value="${machines}"/>
        </bean>
    </property>
    

    In this example, the value for 'machines' is loaded from the properties file.

    If an existing utility method does not meet your needs, it is pretty straightforward to create your own. This technique allows you to execute any static utility method.

    0 讨论(0)
  • 2020-12-02 21:21

    Spring EL makes easier. Java:

    List <String> machines;
    

    Context:

    <property name="machines" value="#{T(java.util.Arrays).asList('${machines}')}"/>
    
    0 讨论(0)
  • 2020-12-02 21:25

    Since Spring 3.0, it is also possible to read in the list of values using the @Value annotation.

    Property file:

    machines=B,C,D
    

    Java code:

    import org.springframework.beans.factory.annotation.Value;
    
    @Value("#{'${machines}'.split(',')}")
    private List<String> machines;
    
    0 讨论(0)
提交回复
热议问题