What exactly is Field Injection and how to avoid it?

I read in some posts about Spring MVC and Portlets that field injection is not recommended. As I understand it, field injection is when you inject a Bean with @Autowired like this:

@Component
public class MyComponent {
    @Autowired
    private Cart cart;
}

During my research I also read about constructor injection:

@Component
public class MyComponent {
    private final Cart cart;

    @Autowired
    public MyComponent(Cart cart){
       this.cart = cart;
    }
}

What are the advantages and the disadvantages of both of these types of injections?


EDIT 1: As this question is marked as duplicate of this question i checked it. Cause there aren’t any code examples neither in the question nor in the answers it’s not clear to me if i’m correct with my guess which injection type i’m using.

4 Answers
4

Leave a Comment