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 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
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations

Trending

  • Comparing Cloud Hosting vs. Self Hosting
  • Java String Templates Today
  • Apache Cassandra With Java: Introduction to UDT
  • Beginner Intro to Real-Time Debugging for Mobile Apps: Tools and Techniques
  1. DZone
  2. Coding
  3. Frameworks
  4. Dependency Injection Pitfalls in Spring

Dependency Injection Pitfalls in Spring

Jakub Kubrynski user avatar by
Jakub Kubrynski
·
Jan. 08, 15 · Interview
Like (0)
Save
Tweet
Share
12.62K Views

Join the DZone community and get the full member experience.

Join For Free
There are three injection variants in Spring framework:
  • Setter-based injection
  • Constructor-based injection
  • Field-based injection
Each of those mechanisms has advantages and disadvantages and there is not only one right approach. For example field injection:
@Autowired
private FooBean fooBean;
It's generally not the best idea to use it in the production code, mostly because it makes our beans impossible to test without starting Spring context or using reflection hacks. On the other hand it requires almost no additional code and could be used in integration tests - which definitely won't be instantiated independently. And in my opinion this is the only case for field-based injections.

Now let's focus on two major variants. In Spring documentation we can read that
...it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.
Also in documentation referring Spring up to 3.1 we could find a sentence
The Spring team generally advocates setter injection, because large numbers of constructor arguments can get unwieldy, especially when properties are optional.
This situation has changed in documentation to fourth version, which says:
The Spring team generally advocates constructor injection as it enables one to implement application components as immutable objects and to ensure that required dependencies are not null. 
Pretty cool especially that prior to version 4.0 people using constructor-based injection where just "some purists" (this also can be found in this documentation) :) Please note that before fourth framework release there used to be a big problem with this injection variant - aspects demanded default constructor. Now there is still one "drawback" of constructor-based injection: it doesn't allow circular dependencies. I intentionally put drawback into quotation marks because for me it's a huge advantage of this mechanism :) One more sentence from the documentation:
It is generally recommended to not rely on circular references between your beans. 
But why? What can happen if we have circular references in our applications? I don't want to write about application design because almost always it's possible to refactor our code and delegate problematic logic to a third bean. There are two significant and unfortunately "silent" problems.

First pitfall

When you invoke ListableBeanFactory.getBeansOfType() method, you can't be sure which beans will be returned. Let's see the code of the DefaultListableBeanFactory class:
if (isCurrentlyInCreation(bce.getBeanName())) {
  if (this.logger.isDebugEnabled()) {
    this.logger.debug("Ignoring match to currently created bean '"
        + beanName + "': " + ex.getMessage());
  }
  // ...
  continue;
}

As you can see if you don't use DEBUG logging level there will be zero information that Spring skipped particular bean in resolution process. If you wanted to get all event handlers you're screwed :)

Second pitfall

Second problem refers to AOP. If you want to have aspect on your bean, please ensure there it's not involved in circular reference - otherwise Spring will create two instances of your bean - one without aspect and the other with proper aspect. Of course still without any information. Surprised?

For me it's enough to stop using circular dependencies in our applications (especially that there are probably more interesting behaviors related to this). But what can we do to get out of the problematic situation? Of course you can use constructor-based injection :) But if you have huge application it's not the best idea to spend many days rewriting all classes to use constructors instead of setters. Fortunately I have good news -allowCircularReferences field in AbstractRefreshableApplicationContext class. Just add single line to application context creation (by the way described in this post)

AnnotationConfigWebApplicationContext applicationContext =
    new AnnotationConfigWebApplicationContext();
applicationContext.setAllowCircularReferences(false);
// rest of context initialization

Finally, to keep you in a good mood I'm pasting one more code snippet from DefaultListableBeanFactory :
catch (NoSuchBeanDefinitionException ex) {
  // Shouldn't happen - probably a result of circular reference resolution...
  if (logger.isDebugEnabled()) {
    logger.debug("Failed to check manually registered singleton with name '"
        + beanName + "'", ex);
  }
}

Have a nice day! :)
Dependency injection Spring Framework

Published at DZone with permission of Jakub Kubrynski, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Comparing Cloud Hosting vs. Self Hosting
  • Java String Templates Today
  • Apache Cassandra With Java: Introduction to UDT
  • Beginner Intro to Real-Time Debugging for Mobile Apps: Tools and Techniques

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

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: