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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
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

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How To Build Web Service Using Spring Boot 2.x
  • Visually Designing Views for Java Web Apps
  • How to Activate New User Accounts by Email
  • How To Read the Properties File Outside the Jar in Spring Boot

Trending

  • Fixing Common Oracle Database Problems
  • Unlocking AI Coding Assistants Part 1: Real-World Use Cases
  • Develop a Reverse Proxy With Caching in Go
  • It’s Not About Control — It’s About Collaboration Between Architecture and Security
  1. DZone
  2. Coding
  3. Frameworks
  4. Autowiring Property Values into Spring Beans

Autowiring Property Values into Spring Beans

By 
Roger Hughes user avatar
Roger Hughes
·
Nov. 01, 11 · Interview
Likes (0)
Comment
Save
Tweet
Share
139.6K Views

Join the DZone community and get the full member experience.

Join For Free

Most people know that you can use @Autowired to tell Spring to inject one object into another when it loads your application context. A lesser known nugget of information is that you can also use the @Value annotation to inject values from a property file into a bean’s attributes.

To demonstrate this requires a few bits and pieces, including a property file:

jdbc.driverClassName=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@on-the-beach:1521:mysid
jdbc.username=john
jdbc.password=lennon

In this example, I’ve got a some simple datasource connection details for an Oracle database, which will be injected into a fake datasource class AutowiredFakaSource:

@Component
public class AutowiredFakaSource {

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

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

  @Value("${jdbc.username}")
  private String userName;

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

  @Value("${java.io.tmpdir}")
  private String tmpDir;

  public AutowiredFakaSource() {
  }

  public String execute() {

    System.out.println("Execute FakaSource");
    return "A Result";
  }

  public String getDriverClassName() {
    return driverClassName;
  }

  public String getUrl() {
    return url;
  }

  public String getUserName() {
    return userName;
  }

  public String getPassword() {
    return password;
  }

  public String getTmpDir() {
    return tmpDir;
  }
}

In terms of this blog, AutowiredFakaSource doesn’t really need to do anything, it just has to be a bean with some attributes. The crux of the whole thing lies in the @Value annotations:

@Value("${jdbc.username}")

...which shows that a value from a property file is referenced using its name and the ${} notation.

The JUnit test below demonstrates that all this works okay.

@Test
  public void testAutowiredPropertyPlaceHolder() {

    System.out.println("Autowired Property PlaceHolder Test.");
    ApplicationContext ctx = new ClassPathXmlApplicationContext("autowired_property_place_holder.xml");

    AutowiredFakaSource fakeDataSource = ctx.getBean(AutowiredFakaSource.class);

    assertEquals("oracle.jdbc.OracleDriver", fakeDataSource.getDriverClassName());
    assertEquals("jdbc:oracle:thin:@on-the-beach:1521:mysid", fakeDataSource.getUrl());
    assertEquals("john", fakeDataSource.getUserName());
    assertEquals("lennon", fakeDataSource.getPassword());
    assertNotNull(fakeDataSource.getTmpDir());
    String expected = System.getProperty("java.io.tmpdir");
    assertEquals(expected, fakeDataSource.getTmpDir());
  }

On last thing to note is the XML configuration file. In the example below, you can see that the XML contains two entries. The first is the PropertyPlaceholderConfigurer class that loads the properties from the jdbc.properties file and second is the

<context:component-scan base-package="miscellaneous.property_placeholder" />

XML element that enables autowiring.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

 <!-- Configurer that replaces ${...} placeholders with values from a properties file -->
 <!-- (in this case, JDBC-related settings for the dataSource definition below) -->
 <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  <property name="locations">
   <list>
    <value>jdbc.properties</value>
    <!-- List other property files here -->
    <!-- value>mail.properties</value -->
   </list>
  </property>
 </bean>

 <!-- Enable autowiring -->
  <context:component-scan base-package="miscillaneous.property_placeholder" /> 

</beans>

Finally, eagle eyed readers will have spotted that the @Value annotation also allows you to load system properties. In this example I’ve loaded the Java temp directory path using:

@Value("${java.io.tmpdir}")

…and then tested it using the final assert in the unit test:

 

From http://www.captaindebug.com/2011/10/autowiring-property-values-into-spring_28.html

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
  • How to Activate New User Accounts by Email
  • How To Read the Properties File Outside the Jar in Spring Boot

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • 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:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!