TechieHints SOFTWARE

Property File Configuration for Java Bean in Spring

Here is 2 simple steps to configure property file in Spring ,

Step 1:  Prepare Bean for property file.

Sample property File:
app.image.path=f:/temp1/

Bean Configuration:

@Component
@PropertySource(value = "classpath:app-resources.properties")
@Scope ( scopeName = ConfigurableBeanFactory.SCOPE_SINGLETON )
public class Resources 


              @Value( value = "$app.image.path" ) 
             private String fileImagePath;

             // Add getters and Setters

Step 2: Resolve arguments for $…

Configure PropertySourcesPlaceholderConfigurer in the container or bean.

Using Annotation based configuration:

Add ,
     @Bean
public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer()
return new PropertySourcesPlaceholderConfigurer();

For XML Configuration,

 <bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
          <property name="environment">
              <bean class="org.springframework.web.context.support.StandardServletEnvironment"/>
          </property>
 </bean>

 

Possible Exception if Step 2: is missed:

 Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'app.image.path' in string value "$app.image.path"

Leave a comment