Home > Back-end >  Spring - different forms of constructor injection?
Spring - different forms of constructor injection?

Time:10-14

What are the differences between the following types of Constructor injection in Spring?

@Component
public class MyService {

    private final MyRepository myRepository;

    public MyService(@Autowired MyRepository myRepository) {
        this.myRepository = myRepository;
        }
        
        //rest of code
}

and

@Component
public class MyService {

    private final MyRepository myRepository;

    @Autowired
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
        }
        
        //rest of code
}

Also - which one is better practice?

CodePudding user response:

When you are doing constructor injection . You do not even have to write @Autowired. Spring automatically looks for bean and inject it . If you remove the autowired from above . It will still work

CodePudding user response:

You can use Constructor injections as below this is considered as the better practice

@Component
public class MyService {

    private final MyRepository myRepository;

    @Autowired
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
        }
        
        //rest of code
}

but there is no difference in both forms of constructor injection. and one thing more you don't have to declare the object in constructor injection as you can do it like this in spring boot:

 @Component
 public class MyService {

    @Autowired
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
        }
        
        //rest of code
}

or don't use autowired because the constructor will auto wire automatically like this-

@Component
public class MyService {

    private final MyRepository myRepository;

    //autowire by constructor
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
        }
        
        //rest of code
}

In the below form it does not require Autowired, it will work though, but it doesn't mean anything. The best practice is you use constructor injection as above forms.

@Component
public class MyService {

    private final MyRepository myRepository;

    public MyService(@Autowired MyRepository myRepository) {
        this.myRepository = myRepository;
        }
        
        //rest of code
}
  • Related