Girija Sankar Panda
1 min readMay 20, 2021

--

@PropertySource in Spring framework

Like every other framework, spring has a convenient option to use System properties/User-defined properties throughout the application. By using @PropertySource you will get all the configuration from below mentioned places.

  1. System Environment Variables
  2. JVM Parameters
  3. Properties located in the classpath
  4. Properties located in the file system
  5. Servlet Parameters
  6. JNDI properties

Well.. then how to use it?

So before using the property in any specific class, the property needs to be imported from the respective place.

@Configuration
@PropertySource(“classpath:app.properties”)
public class ApplicationConfig { //… }

Here @Configuration is used to register the class as Spring Bean. @PropertySource is used to configure all the properties of app.properties

ok.Then how to read the required property.Let’s put below content inside app.properties

app.name=demo

By using @Value annotation, the property can be fetched.

@Configuration
@PropertySource(“classpath:app.properties”)
public class ApplicationConfig {
@Value("${app.name}")
String appName;
@Value("${JAVA_HOME}") //JAVA_HOME is System property
String javaHome;
public String getAppName(){return this.appName;}}

Can we import multiple properties in the same file? The answer is yes.

If we are running our application on JDK 8 or more then we can use @PropertySource multiple times as it is a repeatable annotation or else it needs to wrapped by @PropertySources.

#Before Java 8
@PropertySources({
@PropertySource("classpath:foo.properties"), @PropertySource("file:./bar.properties")
})
public class ApplicationConfig {\\}
#After Java 8

@PropertySource("classpath:foo.properties"), @PropertySource("file:./bar.properties")
public class ApplicationConfig {\\}

Thanks for reading.Hope you like it.

--

--