Spring @PropertySources Annotation Example

0

Spring annotation @PropertySource annotation provides a convenient way to add property sources to spring environment. We can specify name of the property source and resource location(s) of the properties file to be loaded. Any placeholders within the location path will be resolved using the existing property sources already registered with the Environment. Each property source will be added in the order in which it is declared.

@PropertySource Example

In this example, we will use @PropertySource to add a properties from file x.properties. x.properties is located in classpath at com/javarticles/spring/annotations.

x.properties:

topic=spring annotations
more=z

In the main method, we create the application context using AnnotationConfigApplicationContext and the register the current class. We next get the environment object and print one of the property from x.properties. One can register multiple classes containing @Configuration.

Instead of getting the Environment object from the context, one can also autowire the environment into the configuration class.

If we registered multiple @Configuration class containing multiple @PropertySource annotation, then the property sources will be added to the environment in the order in which the classes are registered and in the order in which the resource locations are found within a @PropertySource.

SpringPropertySourceAnnotationExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(name="x", 
value="classpath:com/javarticles/spring/annotations/x.properties")
public class SpringPropertySourceAnnotationExample {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringPropertySourceAnnotationExample.class);
            ctx.refresh();
            Environment env = ctx.getEnvironment();
            System.out.println("Topic: " + env.getProperty("topic"));
        } finally {
            ctx.close();
        }
    }

}

Output:

Jan 26, 2016 4:15:32 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:15:32 IST 2016]; root of context hierarchy
Topic: spring annotations
Jan 26, 2016 4:15:32 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:15:32 IST 2016]; root of context hierarchy

Multiple PropertSource Resources

You can also specify multiple resource locations in a @PropertySource. For example, we will add x.properties and y.properties to the environment.

x.properties:

topic=spring annotations
more=z

y.properties:

[email protected] Annotation
more=z

The value attribute of PropertySource is of type string array so you can specify multiple location resources.

SpringMultiplePropertySourceAnnotationExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(name="xy", 
value = {
        "classpath:com/javarticles/spring/annotations/x.properties",
        "classpath:com/javarticles/spring/annotations/y.properties"        
})
public class SpringMultiplePropertySourceAnnotationExample {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringMultiplePropertySourceAnnotationExample.class);
            ctx.refresh();
            Environment env = ctx.getEnvironment();
            System.out.println("Topic: " + env.getProperty("topic"));
            System.out.println("Example: " + env.getProperty("example"));
        } finally {
            ctx.close();
        }
    }

}

Environment contains properties from both the files.

Output:

Jan 26, 2016 4:21:21 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:21:21 IST 2016]; root of context hierarchy
Topic: spring annotations
Example: @PropertySource Annotation
Jan 26, 2016 4:21:21 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:21:21 IST 2016]; root of context hierarchy

Unresolvable Property Source

If the property source location is un-resolvable or the resource is not found then spring will throw a fatal error.
If the property source has a place holder which cannot be resolved.

java.lang.IllegalArgumentException: Could not resolve placeholder 'unresolvable' in string value "classpath:${unresolvable}/unknown.properties"

If the resource can’t be found at the specified location then:

java.io.FileNotFoundException: class path resource [com/javarticles/spring/annotations/n.properties] cannot be opened because it does not exist

In the below example, we have a place holder which couldn’t be resolved.

SpringPropertySourceUnresolvableExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration
@PropertySource(value="classpath:${unresolvable}/unknown.properties")
public class SpringPropertySourceUnresolvableExample {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringPropertySourceUnresolvableExample.class);
            ctx.refresh();           
        } finally {
            ctx.close();
        }
    }

}

Output:

Jan 26, 2016 4:24:05 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:24:05 IST 2016]; root of context hierarchy
Jan 26, 2016 4:24:05 PM org.springframework.context.annotation.AnnotationConfigApplicationContext refresh
WARNING: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.javarticles.spring.annotations.SpringPropertySourceUnresolvableExample]; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'unresolvable' in string value "classpath:${unresolvable}/unknown.properties"
Exception in thread "main" org.springframework.beans.factory.BeanDefinitionStoreException: Failed to parse configuration class [com.javarticles.spring.annotations.SpringPropertySourceUnresolvableExample]; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'unresolvable' in string value "classpath:${unresolvable}/unknown.properties"
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:181)
	at org.springframework.context.annotation.ConfigurationClassPostProcessor.processConfigBeanDefinitions(ConfigurationClassPostProcessor.java:321)
	at org.springframework.context.annotation.ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry(ConfigurationClassPostProcessor.java:243)
	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanDefinitionRegistryPostProcessors(PostProcessorRegistrationDelegate.java:273)
	at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:98)
	at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:678)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:520)
	at com.javarticles.spring.annotations.SpringPropertySourceUnresolvableExample.main(SpringPropertySourceUnresolvableExample.java:14)
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'unresolvable' in string value "classpath:${unresolvable}/unknown.properties"
	at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
	at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
	at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
	at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
	at org.springframework.core.env.AbstractEnvironment.resolveRequiredPlaceholders(AbstractEnvironment.java:571)
	at org.springframework.context.annotation.ConfigurationClassParser.processPropertySource(ConfigurationClassParser.java:358)
	at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:254)
	at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:231)
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:198)
	at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:167)
	... 7 more

Ignore Unresolvable Property Source

By default if spring is unable to read the properties file then it will throw error. In case you want it to ignore the unresolvable property sources and not throw any error then set attribute ignoreResourceNotFound to true.

SpringPropertySourceIgnoreUnresolvableErrorExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(name="unknown",
                value="classpath:${unresolvable}/unknown.properties",
                ignoreResourceNotFound=true)
public class SpringPropertySourceIgnoreUnresolvableErrorExample {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringPropertySourceIgnoreUnresolvableErrorExample.class);
            ctx.refresh();     
            Environment env = ctx.getEnvironment();
            System.out.println(env);
        } finally {
            ctx.close();
        }
    }
}

Output:

Jan 26, 2016 4:31:52 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:31:52 IST 2016]; root of context hierarchy
StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[systemProperties,systemEnvironment]}
Jan 26, 2016 4:31:52 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:31:52 IST 2016]; root of context hierarchy

Default PropertySource Resource

If a property source is unresolvable, you can always resort to a default property source. For example, in classpath:${unknownProperty:com/javarticles/spring/annotations}/x.properties, property unknownProperty doesn’t exist so the default path specified after : is used.

SpringPropertySourceUnresolvableWithDefaultExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@PropertySource(value="classpath:${unknownProperty:com/javarticles/spring/annotations}/x.properties")
public class SpringPropertySourceUnresolvableWithDefaultExample {
    
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringPropertySourceUnresolvableWithDefaultExample.class);
            ctx.refresh();
           
            Environment env = ctx.getEnvironment();
            System.out.println(env.getProperty("topic"));
        } finally {
            ctx.close();
        }
    }    
}

Output:

Jan 26, 2016 4:48:04 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:48:04 IST 2016]; root of context hierarchy
spring annotations
Jan 26, 2016 4:48:04 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:48:04 IST 2016]; root of context hierarchy

@PropertySources Example

If there are multiple PropertySources, you can use annotation @PropertySources which aggregates several PropertySource annotations. In each @PropertySource, you can specify one or more resource locations.

SpringPropertySourcesAnnotationExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

@Configuration
@PropertySources({
    @PropertySource("classpath:com/javarticles/spring/annotations/x.properties"),
    @PropertySource("classpath:com/javarticles/spring/annotations/y.properties")
})
public class SpringPropertySourcesAnnotationExample {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringPropertySourcesAnnotationExample.class);
            ctx.refresh();
            Environment env = ctx.getEnvironment();
            System.out.println("Topic: " + env.getProperty("topic"));
            System.out.println("Example: " + env.getProperty("example"));
        } finally {
            ctx.close();
        }
    }

}

Output:

Jan 26, 2016 4:52:37 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:52:37 IST 2016]; root of context hierarchy
Topic: spring annotations
Example: @PropertySource Annotation
Jan 26, 2016 4:52:37 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.spring[email protected]4783da3f: startup date [Tue Jan 26 16:52:37 IST 2016]; root of context hierarchy

PropertySource with Place Holders

You can specify ${...} placeholders in the resource location path. Spring will resolve the place holders using the already registered property sources.
For example, classpath:com/javarticles/spring/annotations/${more}.properties contains placeholder ${more}. Before spring gets to register ${more}.properties, it already loads x.properties. Property more is set to z so spring resolves ${more}.properties to z.properties.

x.properties:

topic=spring annotations
more=z

z.properties:

topic=spring jpa

SpringPropertySourcesAnnotationPropertyHolderExample:

package com.javarticles.spring.annotations;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.annotation.PropertySources;
import org.springframework.core.env.Environment;

@Configuration
@PropertySources({
    @PropertySource("classpath:com/javarticles/spring/annotations/x.properties"),
    @PropertySource("classpath:com/javarticles/spring/annotations/${more}.properties"),
})
public class SpringPropertySourcesAnnotationPropertyHolderExample {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
        try {
            ctx.register(SpringPropertySourcesAnnotationPropertyHolderExample.class);
            ctx.refresh();
            Environment env = ctx.getEnvironment();
            System.out.println("topic: " + env.getProperty("topic"));
        } finally {
            ctx.close();
        }
    }
}

Output:

Jan 26, 2016 5:10:51 PM org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
INFO: Refreshing org.spring[email protected]4783da3f: startup date [Tue Jan 26 17:10:51 IST 2016]; root of context hierarchy
topic: spring jpa
Jan 26, 2016 5:10:51 PM org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
INFO: Closing org.spring[email protected]4783da3f: startup date [Tue Jan 26 17:10:51 IST 2016]; root of context hierarchy

Download the source code

This was an example about Spring @PropertySources Annotation.

You can download the source code here: springPropertySourcesAnnotationExample.zip
Share.

Comments are closed.