java – declare spring bean of string type one line

java – declare spring bean of string type one line

For readability I would still prefer keeping it all in the context file and also I can redeploy the context file separately to the classpath without having to redeploy the whole .jar

If you want to keep everything in the context file and want to simplify it then you should be using PropertyPlaceholderConfigurer instead of String beans.

Here is an example,

  1. Create a properties file named as project.properties.
  2. Put all your Strings inside that file as {key=value} pair. For Example,

    myStrings.cnst1=FOO
    myStrings.cnst2=BAR
    myStrings.cnst3=FOOBAR
    
  3. Now, declare a PropertyPlaceholderConfigurer inside your context file as follows:

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

  4. Now, you can easily access the values as follows:

    @Value(${myStrings.cnst1})
    private String someString;
    

Refer this link and this link for more information.

java – declare spring bean of string type one line

Leave a Reply

Your email address will not be published. Required fields are marked *