Configuring access to custom property file

In this post under Spring Core, I will show with example how to configure access to custom property file.

In the last blog I showed with example how to access system and environment properties.

But those are not the only properties that we need access to.

We developers also need access to properties created by us in the source code.

The properties created by us are stored in “.properties” file.

To access them we take help of “@PropertySource” annotation.

For out example lets take the “app1.properties” file with below entries

name=Sam Fisher
location=United States

Next I will show the main code, that gives you an example of how to access them in the source code.

Main class

1  package package36;
2  
3  import org.springframework.beans.factory.annotation.Autowired;
4  import org.springframework.context.ApplicationContext;
5  import org.springframework.context.annotation.AnnotationConfigApplicationContext;
6  import org.springframework.context.annotation.Configuration;
7  import org.springframework.context.annotation.PropertySource;
8  import org.springframework.core.env.Environment;
9  
10 @Configuration
11 @PropertySource("app1.properties")
12 public class Example36 {
13     @Autowired
14     private Environment environment;
15 
16     public static void main(String[] args) {
17         ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Example36.class);
18         Example36 example36 = applicationContext.getBean(Example36.class);
19         String result = example36.getEnvironment().getProperty("name");
20         System.out.println(result);
21     }
22 
23     public Environment getEnvironment() {
24         return environment;
25     }
26 
27     public void setEnvironment(Environment environment) {
28         this.environment = environment;
29     }
30 }

In the above code at line 11, I have added “@PropertySource” annotation at the class level and provided the properties file name as an argument.

This properties file should be present in the classpath so that it can be accessed by the application code.

The way we access individual properties in the properties file is similar to way we access environment or system properties that is by calling “getProperty” method on an instance of “Environment” class. Refer to line 19.

This is all we need to do, to configure access to custom properties file.

Leave a comment