DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Visually Designing Views for Java Web Apps
  • Spring Boot – How to Change Default Context Path Using the application. properties?
  • How to Activate New User Accounts by Email

Trending

  • Message Construction: Enhancing Enterprise Integration Patterns
  • Bad Software Examples: How Much Can Poor Code Hurt You?
  • Running Unit Tests in GitHub Actions
  • Exploring the Evolution and Impact of Computer Networks
  1. DZone
  2. Coding
  3. Frameworks
  4. Properties with Spring

Properties with Spring

Starting with Spring 3.1, the new Environment and PropertySource abstractions simplify working with properties.

Eugen Paraschiv user avatar by
Eugen Paraschiv
·
Mar. 04, 13 · Tutorial
Like (6)
Save
Tweet
Share
194.38K Views

Join the DZone community and get the full member experience.

Join For Free

1. Overview

Spring has always tried to be as transparent as possible when it comes to working with properties. Before Spring 3.1 however, the mechanism of both adding new sources of properties into Spring as well as actually using the properties wasn’t as flexible and as robust as it could be.

Starting with Spring 3.1, the new Environment and PropertySource abstractions simplify working with properties. The default Spring Environment now contains two property sources: the System properties and the JVM properties, with the System properties having precedence.

For more information on the unified property management in Spring 3.1, see this official article.

2. Registering Properties via the XML namespace

In an XML configuration, new property files can be made accessible to Spring via the following namespace element:

<context:property-placeholder location="com/foo/foo.properties"/>


3. Registering Properties via Java Annotations

Spring 3.1 also introduces the new @PropertySource annotation, as a convenient mechanism of adding property sources to the environment. This annotation is to be used in conjunction with Java based configuration and the @Configuration annotation:

@PropertySource("classpath:/com/foo/foo.properties")

As opposed to using XML namespace element, the Java @PropertySource annotation does not automatically register a PropertySourcesPlaceholderConfigurer with Spring. Instead, the bean must be explicitly defined in the configuration to get the property resolution mechanism working. The reasoning behind this unexpected behavior is by design and documented on this issue.


4. Behind the Scenes – the Spring Configuration

4.1. Before Spring 3.1

Since the convenience of defining property sources with annotations was introduced in the recently released Spring 3.1, XML based configuration was necessary in the previous versions.

Defining a <context:property-placeholder> XML element automatically registers a new PropertyPlaceholderConfigurer bean in the Spring Context. This is also the case in Spring 3.1 if, for backwards compatibility purposes, the XSD schemas are not updated to the 3.1 versions.

4.2. In Spring 3.1

From Spring 3.1 onward, the XML <context:property-placeholder> will no longer register the old PropertyPlaceholderConfigurer but the newly introduced PropertySourcesPlaceholderConfigurer. This replacement class was created be more flexible and to better interact with the newly introduced Environment and PropertySource mechanism; it should be considered the standard for 3.1 applications.


5. Properties by hand in Spring 3.0 – PropertyPlaceholderConfigurer

Besides the convenient methods of getting properties into Spring – annotations and the XML namespace – the property configuration bean can also be defined and registered manually. Working with the PropertyPlaceholderConfigurer gives us full control over the configuration, with the downside of being more verbose and most of the time, unnecessary.

5.1. Java configuration

@Bean
public static PropertyPlaceholderConfigurer properties(){
   PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
   Resource[] resources = new ClassPathResource[ ]
      { new ClassPathResource( "foo.properties" ) };
   ppc.setLocations( resources );
   ppc.setIgnoreUnresolvablePlaceholders( true );
   return ppc;
}


5.2. XML configuration

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
      <list>
         <value>classpath:foo.properties</value>
      </list>
   </property>
   <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>


6. Properties by hand in Spring 3.1 – PropertySourcesPlaceholderConfigurer

Similarly, in Spring 3.1, the new PropertySourcesPlaceholderConfigurer can also be configured manually:

6.1. Java configuration

@Bean
public static PropertySourcesPlaceholderConfigurer properties(){
   PropertySourcesPlaceholderConfigurer pspc =
      new PropertySourcesPlaceholderConfigurer();
   Resource[] resources = new ClassPathResource[ ]
      { new ClassPathResource( "foo.properties" ) };
  pspc.setLocations( resources );
  pspc.setIgnoreUnresolvablePlaceholders( true );
  return pspc;
}


6.2. XML configuration

<bean class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
  <property name="location">
  <list>
  <value>classpath:foo.properties</value>
  </list>
  </property>
  <property name="ignoreUnresolvablePlaceholders" value="true"/>
</bean>


7. Using properties in Spring

Both the older PropertyPlaceholderConfigurer and the new PropertySourcesPlaceholderConfigurer added in Spring 3.1 resolve ${…} placeholders within bean definition property values and @Value annotations.

For example, to inject a property using the @Value annotation:

@Value( "${jdbc.url}" ) private String jdbcUrl;

Using properties in Spring XML configuration:

<bean id="dataSource">
   <property name="url" value="${jdbc.url}" />
</bean>

And lastly, obtaining properties via the new Environment APIs:

@Autowired
private Environment env;
...
dataSource.setUrl(env.getProperty("jdbc.url"));


7.1 Properties Search Precedence

By default, in Spring 3.1, local properties are search last, after all environment property sources, including property files. This behavior can be overridden via the localOverride property of the PropertySourcesPlaceholderConfigurer, which can be set to true to allow local properties to override file properties.

In Spring 3.0 and before, the old PropertyPlaceholderConfigurer also attempted to look for properties both in the manually defined sources as well as in the System properties. The lookup precedence was also customizable via the systemPropertiesMode property of the configurer:

  • never – Never check system properties
  • fallback (default) – Check system properties if not resolvable in the specified properties files
  • override – Check system properties first, before trying the specified properties files. This allows system properties to override any other property source.


8. Conclusion

This article covered the various ways to work with Properties in Spring, discussing both the older Spring 3.0 and below and the new support for properties, introduced in Spring 3.1. For a project making heavy use of properties, check out the github project.

If you read this far, you should follow me on twitter here.

Property (programming) Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Visually Designing Views for Java Web Apps
  • Spring Boot – How to Change Default Context Path Using the application. properties?
  • How to Activate New User Accounts by Email

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: