DZone
Java Zone
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
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > Spring Core: Dependency Injection

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.

Gaurav Rai Mazra user avatar by
Gaurav Rai Mazra
·
Feb. 14, 17 · Java Zone · Tutorial
Like (26)
Save
Tweet
23.92K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Dependency injection Spring Framework

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • SQL vs. NoSQL: Pros and Cons
  • 5 Myths of Kubernetes
  • What Are Microservices?
  • How to Submit a Post to DZone

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • MVB Program
  • 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
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo