PropertySource in Spring
PropertySource in Spring
The @PropertySource annotation lets you load and register external configuration properties from a file or resource into the Spring Environment.
This helps you externalise configuration settings and keep them separate from your application code, making them easier to manage and maintain.
@PropertySource is commonly used with @Configuration classes. It allows you to load properties from various sources like .properties files, .yml files, or even custom sources.
Here’s how to use @PropertySource:
1. Create a properties file
First, create an external properties file, such as custom-config.properties, and add some key-value pairs:
app.name=My Custom Application
app.version=1.0.0
2. Create a configuration class
Now create a @Configuration class and use the @PropertySource annotation to specify the properties file you want to load:
@Configuration
@PropertySource("classpath:custom-config.properties")
public class CustomConfig {
// Your configuration code goes here
}
In this example, we’re loading the custom-config.properties file from the classpath.
3. Inject properties
You can now inject the properties from the custom-config.properties file into your beans using the @Value annotation:
@Component
public class MyService {
@Value("${app.name}")
private String appName;
@Value("${app.version}")
private String appVersion;
// Your service code goes here
}
Using Environment
Alternatively, you can inject the Environment object and access the properties using the getProperty method:
@Component
public class MyService {
private final Environment environment;
@Autowired
public MyService(Environment environment) {
this.environment = environment;
}
public void printAppInfo() {
System.out.println("App Name: " + environment.getProperty("app.name"));
System.out.println("App Version: " + environment.getProperty("app.version"));
}
}
@PropertySource can be used multiple times in a @Configuration class to load properties from different sources. If you have a .yml file instead of a .properties file, you can use @PropertySource with a custom PropertySourceFactory to load the .yml file, such as the YamlPropertySourceFactory.