Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is @Autowired annotation mandatory on constructor in Spring boot

Is it mandatory to put @Autowired if I am using constructor DI?

like image 578
Vitalii Avatar asked Apr 18 '18 07:04

Vitalii


People also ask

Can we use @autowired for constructor?

In Spring, you can use @Autowired annotation to auto-wire bean on the setter method, constructor , or a field . Moreover, it can autowire the property in a particular bean. We must first enable the annotation using below configuration in the configuration file. We have enabled annotation injection.

Is @autowired still needed?

Here the quote from the official documentation : As of Spring Framework 4.3, an @Autowired annotation on such a constructor is no longer necessary if the target bean only defines one constructor to begin with.

How do you Autowire a constructor in Spring boot?

Spring container looks at the beans on which autowire attribute is set constructor in the XML configuration file. It then tries to match and wire its constructor's argument with exactly one of the beans name in the configuration file. If matches are found, it will inject those beans.

Is Autowired needed in Spring boot?

In the spring boot, the @Autowired annotation must be used in the constructor with more than one argument. Each argument needs to load a bean different from the ApplicationContext spring boot. The annotation can not be specified in the constructor, as only one bean name can be specified.


Video Answer


1 Answers

Is @Autowired annotation mandatory for a constructor?

No.

After Spring 4.3 If your class has only single constructor then there is no need to put @Autowired.

Before Spring 4.3:

package com.example.service;
    
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
    
@Service
public class DatabaseAccountService implements AccountService {
    
    private final RiskAssessor riskAssessor;
    
    @Autowired
    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }
    
    // ...
}

After:

@Service
public class DatabaseAccountService implements AccountService {
    
    private final RiskAssessor riskAssessor;
    
    public DatabaseAccountService(RiskAssessor riskAssessor) {
        this.riskAssessor = riskAssessor;
    }
    
    // ...
}

Extra: With Lombok, after Spring 4.3

With Lombok you can use @RequiredArgsConstructor to make the code even cleaner:

@Service
@RequiredArgsConstructor
public class DatabaseAccountService implements AccountService {
    private final RiskAssessor riskAssessor; 
}
like image 84
Mehraj Malik Avatar answered Sep 28 '22 03:09

Mehraj Malik