Over a million developers have joined DZone.

Dependency Injection Pitfalls in Spring

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

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! :)

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:

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

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}