shortcut for injecting strings with spring

前端 未结 3 2360
刺人心
刺人心 2021-02-20 01:01

I inject Strings in my spring config by doing the following:


    

        
相关标签:
3条回答
  • 2021-02-20 01:17

    You should not have String beans. Just use their value directly.

    Create a properties file strings.properties and put it on the classpath

    strings.key=Region
    

    Declare a PropertyPlaceholderConfigurer

    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location">
            <value>strings.properties</value>
        </property>
    </bean>
    

    Then annotate instance field Strings as

    @Value("${strings.key}")
    private String key;
    

    Spring will inject the value from the strings.properties file into this key String.

    This obviously assumes that the class in which the @Value annotation appears is a bean managed in the same context as the PropertyPlaceholderConfigurer.

    0 讨论(0)
  • 2021-02-20 01:25

    In addition to the other answers and if you're using Spring 3.1+, you can use the constructor namespace.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:c="http://www.springframework.org/schema/c" <-- add c namespace
      ...
    
    <bean id="someClass" class="a.b.c.SomeClass"
      c:someProperty="Region"
    />
    
    0 讨论(0)
  • 2021-02-20 01:43

    There is no need to create a bean of type String. Just pass the value to constructor-arg:

    <bean id="foo" class="x.y.Foo">
        <constructor-arg value="Region"/>
    </bean>
    

    works.

    0 讨论(0)
提交回复
热议问题