Read Property Value From Properties File In Spring

The Java properties file can be used to store project configurations or settings.

constant.properties

ui.defaultIconUrl=graph.facebook.com/ek.pranav/picture

Environment – Interface representing the environment in which the current application is running.

@Configuration – Configuration classes are candidates for component scanning (typically using Spring XML’s <context:component-scan/> element) and therefore may also take advantage of @Autowired/@Inject at the field and method level (but not at the constructor level).

@PropertySource – Adds property sources to the enclosing Environment.

 

The values in the properties can be accessed by injecting Environment object to the configuration class.

ConstantPropertyInjector.java


@Configuration
@PropertySource("classpath:META-INF/constant.properties")
public class ConstantPropertyInjector {

@Autowired Environment env;

   @Bean
   public ConstantImageHolder getConstantProperty(){
     ConstantImageHolder constant = new ConstantImageHolder ();
     constant.setDefaultIcon(env.getProperty("ui.defaultIconUrl"));
     return constant;
   }

}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s