Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference context:property-placeholder VS @Configuration @PropertySource classpathproperties

Tags:

spring

I need to know difference between below two ways of loading a property file.

Approach-1

 <context:property-placeholder location="classpath:constants.properties"/>

Approach-2

<context:component-scan base-package="com.snippets.enterprise"/>

package com.snippets.enterprise;

@Configuration
@PropertySource("classpath:/constants.properties")
public class SpringConfig  {}

I see in approach two keys and values are available when application context is loading. but in

approach one keys of the properties are not available when application context is loading and it says

key is not found. Please let me know the difference of these two approaches.

  1. When property files are loading with the application context.

  2. When key,values of property files get initialized in the container.

like image 340
Kasun Avatar asked Apr 20 '14 01:04

Kasun


1 Answers

Both are actually quite independent. Let me try and clarify based on my understanding:

Approach 1 of using context:property-placeholder registers a component which can resolve placeholders of form ${propertyname} in bean definitions.

whereas the @PropertySource annotation contributes properties to the active Spring environment.

Now, coming back to Approach 1, context:property-placeholder actually is intelligent enough to know that it needs to look not just at the properties registered through its location attribute but also to look at the properties available in the current active environment(to which properties have been added in through the @PropertySource annotations like in your approach2).

So, if you want your placeholders to continue to be resolved you will need to use your approach1 with approach2.

If on the other hand you want to use approach 2 exclusively then, the best way is to inject in an environment where you need the property and explicitly look for the property, this way:

@Component
public class MyBean {
    @Autowired 
    private Environment environment;

    public void mymethod() {
        ..
        environment.getProperty("mykey");
    }
}
like image 167
Biju Kunjummen Avatar answered Sep 30 '22 17:09

Biju Kunjummen