Saturday, August 17, 2013

Spring: injecting properties file values into Spring managed beans

In this post, we'll go through 3 different ways to configure (XML based) a Spring application, to inject properties file values into its managed beans.

Method 1: <util:properties> schema based configuration element

In the Spring configuration file, import the spring-util schema, then use the <util:properties> element to register a bean of type java.util.properties. This element expects both an id, and a location attribute. The former is necessary to determine from which Properties bean the value we want to inject comes from, while the latter is expected to define which properties file is to be loaded in the Properties bean.

Once a Properties bean has been defined, its values can be injected into Spring managed beans with the following annotation: @Value("#{properties_bean_id[property_name]}")

Example:

Content of the prop1.properties file:


message1=Message from prop1.properties


Spring configuration: 


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

 <context:component-scan base-package="example1" />

 <util:properties id="propSource" location="classpath:/sample-properties/prop1.properties" />
</beans>

Property value injection into Spring managed bean:

@Value("#{propSource[message1]}")



Method 2: <context:property-placeholder> schema based configuration element


This time, in the Spring configuration file, import the spring-context schema, then use the <context:property-placeholder> element to register a bean of type org.springframework.beans.factory.config.PropertyPlaceholderConfigurer. Just like in the previous method, this element expects the location attribute that specifies the properties file to load.

To retrieve a property value, use the syntax as follows: ${property_name}

Example:

Content of the prop2.properties file:

message2=Message from prop2.properties

Spring configuration:


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

 <context:component-scan base-package="example2" />

 <context:property-placeholder location="classpath:/sample-properties/prop2.properties"/>
</beans>



Property value injection into Spring managed bean:

@Value("${message2}")


Method 3: registering bean of type PropertyPlaceholderConfigurer


In this last method, we just have to explicitly register a bean of type org.springframework.beans.factory.config.PropertyPlaceholderConfigurer. Then, we'll need to specify a location property that determines the properties file to be loaded.

The syntax used to retrieve property values is exactly the same as method 2, that is: ${property_name}

Example:

Content of prop3.properties file:

message3=Message from prop3.properties

Spring configuration:

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

 <context:component-scan base-package="example3" />
 
 <bean id="propSource" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="location" value="classpath:/sample-properties/prop3.properties" />
 </bean>
</beans>



Property value injection into Spring managed bean:

@Value("${message3}")

Extra example: defining multiple PropertiesPlaceholderConfigurer (PPC) beans + PPC with multiple properties files




 
 
 
  
  
 
 
 
  
   
    classpath:/sample-properties/prop2.properties
    classpath:/sample-properties/prop3.properties
   
  
 

To define a PropertyPlaceholderConfigurer bean to load multiples properties files, we use the locations property and set its value to a list of properties files.

Another thing we must pay attention to, is when we are defining multiple PropertyPlaceholderConfigurer beans within a same Spring context (in this example, we're defining 2 of them). In this case, we need to specify the ignoreUnresolvablePlaceholders property in the first PPC bean(s) with the value true. Otherwise, the application context will fail to load as Spring, at bean build time, tries to inject a value that resides in a properties file that is to be loaded in another PPC bean. 

More precisely, in this example: the Component4 class expects value injection from prop1.properties, prop2.properties and prop3.properties files. When trying to inject the values from prop2.properties and prop3.properties, the placeholders could not be resolved yet as they depends on the second PPC bean. Therefore, using the ignoreUnresolvablePlaceholders property on the first PPC bean will prevent exceptions from being thrown, and we'll just wait for another PPC bean to be able to inject these values.

Working source code

A sample project to test the different methods we've just went through is available here 

34 comments:

  1. The best knowing spring injections files are into derivative things and i loved it the way you have presented it and thanks for sharing.
    java training centers in bangalore btm

    ReplyDelete
  2. Thanks, nice post

    ReplyDelete
  3. Thanks. Good one. I tried to find something on similar lines, this post was the best.

    ReplyDelete
  4. Thanks for posting this. Well done.

    ReplyDelete
  5. Hi,this is good and Do you which spring API process @Value annotation injection?

    ReplyDelete
    Replies
    1. Actual processing of the @Value annotation is performed by a BeanPostProcessor.
      For more details, you can refer to the Value annotation javadoc:

      http://docs.spring.io/spring/docs/3.1.x/javadoc-api/org/springframework/beans/factory/annotation/Value.html?is-external=true

      Delete
  6. Thnaks for sharing detailed post about injection files in Java.

    ReplyDelete
  7. Thanks for the post.

    ReplyDelete
  8. Candid institute Spring and Hibernate course provides a comprehensive introduction to Spring and Hibernate open source frameworks as well as Web Services and AJAX. Suitable for both Spring3/Hibernate3 and Spring4/Hibernate4, the course includes coverage of the core Spring and Hibernate capabilities, as well as the integration capabilities provided by Spring.
    Spring boot training

    ReplyDelete
  9. The Spring Framework is a lightweight framework for developing Java enterprise applications. It provides high performing, easily testable and reusable code. Spring handles the infrastructure as the underlying framework so that you can focus on your application.Spring is modular in design, thereby making creation, handling and linking of individual components so much easier. Spring implements Model View Container(MVC) design pattern.
    spring mvc validation example

    ReplyDelete
  10. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.
    Best Selenium Training in Chennai | Selenium Training Institute in Chennai | Besant Technologies


    ReplyDelete
  11. Its really an Excellent post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog. Thanks for sharing....
    angularjs online Training

    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    ReplyDelete
  12. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    Best Devops Training in pune

    ReplyDelete
  13. The knowledge of technology you have been sharing thorough this post is very much helpful to develop new idea. here by i also want to share this.
    Best Devops Training in pune

    ReplyDelete
  14. Thank you for allowing me to read it, welcome to the next in a recent article. And thanks for sharing the nice article, keep posting or updating news article.
    online Python training | python training in chennai

    ReplyDelete
  15. It’s great to come across a blog every once in a while, that isn’t the same out of date rehashed material. Fantastic read.
    safety course in chennai

    ReplyDelete
  16. Really great post, I simply unearthed your site and needed to say that I have truly appreciated perusing your blog entries.
    I appreciate that you produced this wonderful article to help us get more knowledge about this topic. I know, it is not an easy task to write such a big article in one day, I've tried that and I've failed. But, here you are, trying the big task and finishing it off and getting good comments and ratings. That is one hell of a job done!

    ReplyDelete
  17. I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .
    Python training in bangalore
    Python course in pune
    Python training in bangalore

    ReplyDelete
  18. Thanks for splitting your comprehension with us. It’s really useful to me & I hope it helps the people who in need of this vital information. 
    excel advanced excel training in bangalore | Devops Training in Chennai

    ReplyDelete
  19. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    angularjs Training in marathahalli

    angularjs interview questions and answers

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs online Training

    ReplyDelete
  20. You’ve got an awful lot of text for only having one or 2 pictures. Maybe you could space it out better?
    fire and safety course in chennai

    ReplyDelete
  21. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    AWS Interview Questions And Answers

    AWS Training in Chennai | Best AWS Training in Chennai

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    ReplyDelete
  22. When I initially commented, I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several emails with the same comment. Is there any way you can remove people from that service? Thanks.

    AWS Interview Questions And Answers

    AWS Training in Chennai | Best AWS Training in Chennai

    AWS Training in Pune | Best Amazon Web Services Training in Pune

    ReplyDelete
  23. Do you have a spam issue on this website; I also am a blogger, and I wanted to know your situation; many of us have developed some nice methods
    health and safrety courses in chennai

    ReplyDelete
  24. Hmm, it seems like your site ate my first comment (it was extremely long) so I guess I’ll just sum it up what I had written and say, I’m thoroughly enjoying your blog. I as well as an aspiring blog writer, but I’m still new to the whole thing. Do you have any recommendations for newbie blog writers? I’d appreciate it.

    AWS Interview Questions And Answers
    AWS Training in Bangalore | Amazon Web Services Training in Bangalore
    AWS Training in Pune | Best Amazon Web Services Training in Pune
    Amazon Web Services Training in Pune | Best AWS Training in Pune
    AWS Online Training | Online AWS Certification Course - Gangboard

    ReplyDelete