@PropertySource and @PropertySources Annotations
In Spring Framework, the @PropertySource annotation is used to specify the source of external property files that contain key-value pairs. These properties can be injected into Spring beans using the @Value annotation or by using the Environment object.
Here’s an example of how to use @PropertySource in a Spring application:
Create a properties file, for example, application.properties, and place it in the classpath of your application. This file can contain key-value pairs like key=value, where the key represents the property name and the value represents the property value.
In your Spring configuration class, annotate it with @PropertySource and specify the location of the properties file. You can specify multiple @PropertySource annotations to load properties from multiple files.
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:application.properties")
public class AppConfig {
// Configuration code...
}
In the example above, application.properties is located in the classpath. You can also specify a file system path using the file: prefix or a URL using the http: or https: prefixes.
Once you have configured the @PropertySource, you can inject the properties into your beans using the @Value annotation or by using the Environment object.
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class MyComponent {
@Value("${key}")
private String value;
// ...
}
In the example above, the value of the key property from the application.properties file will be injected into the value field of the MyComponent bean.
That’s a basic example of how to use @PropertySource in Spring to load external properties into your application. By using this annotation, you can easily externalize configuration and make your application more flexible and configurable.

Leave a Reply