Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shortcut for injecting strings with spring

Tags:

java

spring

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

<bean class="java.lang.String">
    <constructor-arg type="java.lang.String" value="Region" />
</bean>

Is there a shorter way of doing it?

Update: I am using spring 3.0.3.

These are actually used to populate a list:

        <list>
            <bean class="java.lang.String">
                <constructor-arg type="java.lang.String" value="Region" />
            </bean>
            ...

Seems like this works:

<list>
   <value>Region</value>
   <value>Name</value>
   ....

But I agree with the suggestions that this should eventually go in a property and be passed in.

like image 931
naumcho Avatar asked Sep 03 '13 15:09

naumcho


People also ask

What does @inject do in Spring?

@Inject annotation is a standard annotation, which is defined in the standard "Dependency Injection for Java" (JSR-330). Spring (since the version 3.0) supports the generalized model of dependency injection which is defined in the standard JSR-330.


1 Answers

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.

like image 152
Sotirios Delimanolis Avatar answered Sep 17 '22 12:09

Sotirios Delimanolis