Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Spring Core: Dependency Injection

DZone's Guide to

Spring Core: Dependency Injection

Spring newbies may sometimes need a hand with getting the hang of dependency injection. Let's look at constructor- and setter-based injection as well as some advice.

· Java Zone
Free Resource

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.

Dependency injection is a process in which objects define their dependencies, i.e. other objects they require to work, through a constructor, setter methods, factory methods, etc. The container's responsibility is to inject those while creating beans. With dependency injection in place, we have cleaner code and clear way of decoupling. There are two prominent variants of dependency injection.

  • Constructor-based
  • Setter-based

Constructor-Based Dependency Injection

This is when you express your dependencies through constructor arguments and your containers invoke your constructor with the number of arguments and type of arguments expected by the constructor. Let's jump to one quick example:

@Component
public class ConstructorBasedFileParser {
    private Parser parser;

    @Autowired
    public ConstructorBasedFileParser(Parser parser) {
        this.parser = parser;
    }

    public void setParser(Parser parser) {
        this.parser = parser;
    }

    public void parseFile(File file) {
        if (parser.canParse(file)) {
            parser.parse(file);
        }
    }
}


In the above code snippet, ConstructorBasedFileParser is a component that expresses its dependency on Parser through a constructor using @Autowired.

The configuration class for the above code snippet looks like this:

@Configuration
@Import(value = ParserConfig.class)
@ComponentScan(basePackages = "com.gauravbytes.di.parser.constructor")
public class ConstructorBasedDIConfig {

}


@Configuration declares it as Spring Configuration file. @ComponentScan is used along with configuration classes to scan for components. @Import imports one or more configuration classes. It is equivalent to <import/>.

Setter-Based Dependency Injection

Setter-based dependency injection is accomplished by calling setter methods on beans after invoking no-args constructors through the container. Let's jump to an example to see how to use setter method dependency injection.

@Component
public class SetterBasedFileParser {
    private Parser parser;

    public SetterBasedFileParser() {}

    @Autowired
    public void setParser(Parser parser) {
        this.parser = parser;
    }

    public void parseFile(File file) {
        if (parser.canParse(file)) {
            parser.parse(file);
        }
    }
}


In above code snippet, SetterBasedFileParser is a component class that expresses its dependency through setter methods setParser() using @Autowired.

When to Use Constructor-Based vs. Setter-Based DI?

As the Spring documentation states, use constructor-based DI for mandatory dependencies and setter-based DI for optional dependencies. It is advisable to use constructor-based DI. It helps with immutability and also ensures that required dependences are met before constructing that bean. Also, if you want to reconfigure your bean, then use setter-based DI.

Circular Dependencies

There could be a case when your open bean, say A, is dependent on B , and B is dependent on bean A (both expressing dependencies through a constructor). The Spring IoC container will detect this at runtime and will throw BeanCurrentlyInCreationException.

A possible solution is to use setter-based injection in some of the beans.

I hope you find this post useful. You can grab the full example code used on GitHub.

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:
java ,dependency injection ,tutorial ,spring core ,circular dependencies

Published at DZone with permission of Gaurav Rai Mazra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}