Enterprise Java

Spring Injection Types

Spring supports three types of dependency injections:

Constructor injection

01
02
03
04
05
06
07
08
09
10
@Component
public class SecondBeanImpl implements SecondBean {
 
    private FirstBean firstBean;
 
    @Autowired
    public SecondBeanImpl(FirstBean firstBean) {
        this.firstBean = firstBean;
    }
}

That is similar to:

1
2
FirstBean firstBean = new FirstBeanImpl();
SecondBean secondBean = new SecondBeanImpl(firstBean);

This type of dependency injection instantiates and initializes the object.
In this approach, beans are immutable and dependencies are not null. However, if you define many parameters in the constructor, your code is not clean.
From Spring 4.3 the @Autowired annotation is not required if the class has a single constructor.

Setter injection

01
02
03
04
05
06
07
08
09
10
@Component
public class SecondBeanImpl implements SecondBean {
 
    private FirstBean firstBean;
 
    @Autowired
    public setFirstBean(FirstBean firstBean) {
        this.firstBean = firstBean;
    }
}

That is similar to:

1
2
3
FirstBean firstBean = new FirstBeanImpl();
SecondBean secondBean = new SecondBeanImpl();
secondBean.setFirstBean(firstBean);

In this approach, beans are not immutable (the setter could be called later), and not mandatory dependencies can lead to NullPointerExceptions.

Field injection

1
2
3
4
5
6
@Component
public class SecondBeanImpl implements SecondBean {
 
    @Autowired
    private FirstBean firstBean;
}

This approach may look cleaner but hides the dependencies and makes testing difficult. While constructor and setter injections use proxies, field injection uses reflection which could affect the performance. Could be used in test classes.

Published on Java Code Geeks with permission by Eidher Julian, partner at our JCG program. See the original article here: Spring Injection Types

Opinions expressed by Java Code Geeks contributors are their own.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Eidher Julian

Eidher Julian is a Systems Engineer and Software Engineering Specialist with 13+ years of experience as a Java developer. He is an Oracle Certified Associate and SOA Certified Architect.
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button