简体   繁体   中英

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

Spring mappings can be done with XML or with annotations .

In your case, if no XML defined, your MessageSource and Environment classes should be mapped by Spring annotations like @Component @Service or @Resource :

@Component

Indicates that an a nnotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

@Autowired

@Autowired annotation will try to find a bean of type Foo in the spring context and will then inject the same.

@Resource

Similar to this is @Resource annotation that will try to find the bean with the name "foo". To summarize, @Autowired wires by type and @Resource wires by name.

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

Both the Environment and the MessageSource are closely tied to the inner workings of Spring Framework.

The environment is part of the application context and will be available for autowiring.

The ApplicationContext interface extends the MessageSource interface and will be available for autowiring as a message source, even if you have not defined your own message source bean. (If you define your own message source, the application context will delegate to that )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM