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 

42 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
    Replies
    1. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java EE Online Training Students.

      Delete
  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. Thanks so very much for taking your time to create this very useful and informative site. I have learned a lot from your site. Thanks!!


    JAVA Course in Chennai

    ReplyDelete
  9. Thanks for your informative article on Java. It is most popular and reliable software development platform for creating mobile application. JAVA Course in Chennai

    ReplyDelete

  10. Nice blog, here I had an opportunity to learn something new in my interested domain. I have an expectation about your future post so please keep updates.

    Fita Chennai Reviews | JAVA Training in Chennai

    ReplyDelete
  11. Great post and informative blog.it was awesome to read, thanks for sharing this great content to my vision.
    Informatica Training In Chennai
    Hadoop Training In Chennai
    Oracle Training In Chennai
    SAS Training In Chennai

    ReplyDelete
  12. Best SQL Query Tuning Training Center In Chennai This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic..

    ReplyDelete
  13. Thanks so very much for taking your time to create this very useful and informative site. I have learned a lot from your site. Thanks!!
    microstrategy training in chennai

    ReplyDelete
  14. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

    ReplyDelete
  15. In my point of view, this is really very well and informative content given about Spring: injecting properties file values into Spring managed beans. Thanks for given this information here about this blog.
    1bhk Flats for Rent in Pitampura

    ReplyDelete
  16. 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
  17. 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
  18. Impressive share about spring-injecting properties file values into Spring managed beans.office space for rent in chennai

    ReplyDelete
  19. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.

    Best Java Training Institute Chennai

    ReplyDelete
  20. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Best Hadoop Training Institute In chennai

    amazon-web-services-training-institute-in-chennai

    ReplyDelete
  21. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    MEAN stack training in Chennai

    MEAN stack training in bangalore

    MEAN stack training in tambaram

    MEAN stack training in annanagar

    MEAN stack training in Velachery

    MEAN stack training Sholinganallur

    ReplyDelete
  22. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Devops Training in Chennai

    Devops Training in Bangalore

    ReplyDelete
  23. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

    rpa training in Chennai | rpa training in pune

    rpa training in tambaram | rpa training in sholinganallur

    rpa training in Chennai | rpa training in velachery

    rpa online training | rpa training in bangalore

    ReplyDelete
  24. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post I would like to read this
    python training in chennai
    python training in chennai
    python training in Bangalore

    ReplyDelete
  25. This is an awesome post.Really very informative and creative contents. These concept is a good way to enhance the knowledge.I like it and help me to development very well.Thank you for this brief explanation and very nice information.Well, got a good knowledge.
    java training in chennai | java training in bangalore


    java training in tambaram | java training in velachery

    ReplyDelete