Rollerball
Rollerball

Reputation: 13108

Spring @Autowired detection

If I have a class which uses a spring bean, (will be wired via @Autowired). I noticed that not only the class that will be injected needs the @Component but also the class the uses it (inject it). Why is it like that? Should not spring inject wherever @Autowired is? Without having to use @Component for the injector class?

Upvotes: 0

Views: 649

Answers (2)

Tobb
Tobb

Reputation: 12215

In Spring, one works with beans. A bean is a java object that is managed by a spring context. When encountering a bean containing an @Inject, Spring will seach its context for a bean of the type of the variable to be injected. If no such bean is defined, Spring will have nothing to inject. Also, if the class with the @Inject doesn't have a bean, then Spring won't know about it, and thus cannot inject anything into it.

To get Spring to create a bean of a class, several methods are available. Through annotations, the class has to be annotated with @Component, or the more specialized annotations @Service, @Repository and @Controller. Only then will Spring create a bean for the class that can be @Injected into other beans.

Upvotes: 0

WeMakeSoftware
WeMakeSoftware

Reputation: 9162

Spring processes and manages only those classes which are marked by one of stereotype annotations @Component, @Controller, @Repository, @Service.

It does not scan all of your classes (that would make the startup very slow).

If the class is not managed by Spring it does not process any of the annotation inside that particular class.

Upvotes: 2

Related Questions