DEV Community

eidher
eidher

Posted on • Edited on

4

Spring Injection Types

Spring supports three types of dependency injections:

Constructor injection

@Component
public class SecondBeanImpl implements SecondBean {

    private FirstBean firstBean;

    @Autowired
    public SecondBeanImpl(FirstBean firstBean) {
        this.firstBean = firstBean;
    }
}
Enter fullscreen mode Exit fullscreen mode

That is similar to:

FirstBean firstBean = new FirstBeanImpl();
SecondBean secondBean = new SecondBeanImpl(firstBean);
Enter fullscreen mode Exit fullscreen mode

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

@Component
public class SecondBeanImpl implements SecondBean {

    private FirstBean firstBean;

    @Autowired
    public setFirstBean(FirstBean firstBean) {
        this.firstBean = firstBean;
    }
}
Enter fullscreen mode Exit fullscreen mode

That is similar to:

FirstBean firstBean = new FirstBeanImpl();
SecondBean secondBean = new SecondBeanImpl();
secondBean.setFirstBean(firstBean);
Enter fullscreen mode Exit fullscreen mode

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

Field injection

@Component
public class SecondBeanImpl implements SecondBean {

    @Autowired
    private FirstBean firstBean;
}
Enter fullscreen mode Exit fullscreen mode

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.

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay