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
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

How are you handling the data revolution? We want your take on what's real, what's hype, and what's next in the world of data engineering.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

SBOMs are essential to circumventing software supply chain attacks, and they provide visibility into various software components.

Related

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Implement Hibernate Second-Level Cache With NCache
  • Modify JSON Data in Postgres and Hibernate 6
  • Top 10 C# Keywords and Features

Trending

  • How to Troubleshoot Common Linux VPS Issues: CPU, Memory, Disk Usage
  • Spring Cloud LoadBalancer vs Netflix Ribbon
  • Leveraging AI: A Path to Senior Engineering Positions
  • Seata the Deal: No More Distributed Transaction Nightmares Across (Spring Boot) Microservices

Autowiring Using @Value and Optional Properties

By 
Roger Hughes user avatar
Roger Hughes
·
Feb. 07, 12 · Interview
Likes (10)
Comment
Save
Tweet
Share
151.1K Views

Join the DZone community and get the full member experience.

Join For Free

Last October I wrote a blog entitled Autowiring Property Values into Spring Beans describing how to use Spring’s @Value annotation to inject property values into your beans from both a property file and Java system properties. Last week, I came across this little gotcha whilst helping out on another project....

This project was quite rightly re-using a module written as part of a different project. One of the module's tasks was to process a query string and it had a root url property that could be optionally injected to help with various bits of this processing. The original project that used this module was able to supply the handy root url property, whilst the project that re-used the module couldn’t. This meant that that when the web-server started up an exception similar to the one below was thrown...

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'autowiredFakaSource': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String miscillaneous.property_placeholder.AutowiredFakaSource.optional; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'optional'
 at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
 at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
 at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
 at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
 at …. shortened for readability.


It turns out that, when autowiring properties using @Value, one of the things that you can’t do is to specify the injected property as optional. This seems like a bit of an over-sight by the Guys at Spring as you can make autowired injected objects optional using:


  @Autowired(required = false)
  private MyPojo anotherObject;


There are couple of work arounds for this problem. The first is to ensure that your project’s .properties file contains an empty place holder property. For example one of your Spring components contains something like this:


  @Value("${optional}")
  private String optionalPropertyValue;


...then your .properties file should contain an empty entry like this:


optional=


In this case, Spring will inject an empty string into your component and your code should run.


The second work around is to make use of the 'default value' functionality. For example, suppose that you wanted to make life easy for the folks that are going to use your application. One of the things you can do is to code in default values for your properties so that your users don't have to bother. For example, the following:

  @Value("${useDefault:ThisValue}")
  private String defaultValue;

...will inject ThisValue into defaultValue if a property called useDefault cannot be found. Taking this one step further, then specifying:

  @Value("${emptyDefault:}")
  private String emptyValue;


...will inject an empty string into emptyValue.


If there’s a Spring suggestion box for minor, trivial improvements, then I’d like to suggest that you should be able to make properties optional, perhaps using something like this...

  @Value("${optional}" required=false)
  private String optionalPropertyValue;

...as a convenience feature that might save someone some heart-ache and time in the future.

 

From http://www.captaindebug.com/2012/01/autowiring-using-value-and-optional.html

Property (programming)

Opinions expressed by DZone contributors are their own.

Related

  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  • Implement Hibernate Second-Level Cache With NCache
  • Modify JSON Data in Postgres and Hibernate 6
  • Top 10 C# Keywords and Features

Partner Resources

×

Comments

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
  • [email protected]

Let's be friends: