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
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
  1. DZone
  2. Coding
  3. Frameworks
  4. 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 · Tutorial
Like (26)
Save
Tweet
Share
24.28K 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

  • Using the PostgreSQL Pager With MariaDB Xpand
  • How To Generate Code Coverage Report Using JaCoCo-Maven Plugin
  • Web Application Architecture: The Latest Guide
  • A Complete Guide to AngularJS Testing

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
  • +1 (919) 678-0300

Let's be friends: