Search code examples
javaspringspring-mvcannotationsspring-annotations

How are injected these classes into my Spring controller class?


I am pretty new in Spring and I have some doubts about how is injected some classes into a controller class.

Into my project I have this HomeController class:

@Controller
public class HomeController {

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
    @Autowired
    private MessageSource  messageSource;
    @Autowired
    private Environment env;

    .....................................................
    .....................................................
    .....................................................
}

My doubt is related to the 2 objects MessageSource messageSource and Environment env classes.

As you can see these classes are injected by the @Autowired annotation.

The problem is that I have not bean definition into my XML configuration for these classes. So why are correctly injected? Where are the definition of these bean?

Tnx


Solution

  • Automatic discovery of beans is based on the following rules:

    1) Use context:annotation-config tag in spring-config.xml to let Spring use Annotations
    2) Use context:component-scan tag in spring-config.xml and tell Spring the package in which to look for auto-discovering beans
    3) Use @Component annotation to mark a class as a Spring auto-discoverable bean

    If @Component annotation is used, then the bean declarations need not be declared in spring-config.xml