Tao
Tao

Guide to Using Spring PropertySource

The PropertySource is an interface in the Spring Framework that provides a source for properties (configurations). It allows loading and accessing property values within an application, which are typically used to configure the application’s behavior.

The PropertySource interface defines the following methods:

  • String getName(): Gets the name of the property source.
  • Object getProperty(String name): Retrieves the property value based on the property name.
  • boolean containsProperty(String name): Checks if the property source contains a property with the specified name.

The implementations of the PropertySource interface can load properties from different sources, for example:

  • MapPropertySource: Loads properties from a Map object.
  • SystemEnvironmentPropertySource: Loads properties from the operating system’s environment variables.
  • SystemPropertiesPropertySource: Loads properties from Java system properties.
  • ResourcePropertySource: Loads properties from a file or resource.
  • JndiPropertySource: Loads properties from JNDI (Java Naming and Directory Interface).
  • Custom implementation: You can also create a custom PropertySource implementation to load properties from other sources.

A demo showcasing how to customize a PropertySource to adjust an application’s behavior. This demo dynamically creates different beans based on the property values from a configuration file. You can find the related code on GitHub.

PropertySource.java

@PropertySource("/META-INF/application.property")
public class ApplicationPropertySourceDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ApplicationPropertySourceDemo.class);

        context.refresh();

        context.close();
    }
    @Bean("odd")
    @Conditional(OddPropertyValueCondition.class)
    public String odd(@Value("${even}") String odd){
        System.out.println("Getting odd number through property: " + odd);
        return odd;
    }
    @Bean
    @Conditional(EvenPropertyValueCondition.class)
    public String even(@Value("${even}") String even){
        System.out.println("Getting even number through property: " + even);
        return even;
    }
}

In a Spring application, PropertySources defined in configuration files (such as application.properties or application.yml) can be used to load properties. These properties can be used throughout the application’s components, such as annotation configurations, XML configurations, Java configurations, and more.

By using PropertySource, you can achieve application configurability and flexibility, allowing the application’s behavior to be dynamically adjusted based on the property values without modifying the code.

Related Content