Spring Builders

Michael Isvy
Michael Isvy

Posted on • Updated on

Why do we need to use @Autowired inside Spring Boot Tests?

Starting from Spring 5, we don't need to specify @Autowired inside a Spring bean.

For instance I can do this and it works just fine:

@Service
public class OwnerService {
    private final OwnerRepository ownerRepository;

    public OwnerService(OwnerRepository ownerRepository) {
        this.ownerRepository = ownerRepository;
    }
}
Enter fullscreen mode Exit fullscreen mode

However, in a Spring Boot test, @Autowired still has to be explicit.

@SpringBootTest
public class VisitServiceTest {
    private final VisitService visitService;

    @Autowired
    public VisitServiceTest(VisitService visitService) {
        this.visitService = visitService;
    }
}
Enter fullscreen mode Exit fullscreen mode

Anybody understands why Spring Boot Tests are different?

Top comments (2)

Collapse
 
michael_isvy_13067a826322 profile image
Michael Isvy

thanks Stephane!

Collapse
 
snicoll profile image
Stéphane Nicoll

JUnit is creating your test, not Spring. The autowiring support there is actually an integration between JUnit and Spring and autowiring is just one kind of parameter that you can inject there.