About AnnotationConfigApplicationContext in Spring framework

混江龙づ霸主 提交于 2019-12-13 02:44:52

问题


I have written the following simple stand-alone spring app:

package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;

@Configuration
@ComponentScan(basePackages = { "com.example" })
@PropertySource(ignoreResourceNotFound = true, value = "classpath:/application.props")
public class MainDriver {

@Autowired
private Environment env;
@Autowired
private ApplicationContext ctx;
@Autowired
private ConfigurableEnvironment cenv;

public static void main(String[] args) {

    ApplicationContext ctx = new AnnotationConfigApplicationContext(MainDriver.class);
    MainDriver l = ctx.getBean(MainDriver.class);
    System.out.println("In main() the ctx is " + ctx);
    l.test();

}

public void test() {
    System.out.println("hello");
    System.out.println("env is " + env);
    System.out.println("cenv is " + cenv);
    System.out.println("ctx is" + ctx);
}
}

I understood that within main() we are Creating a new Application context and then creating Bean and eventually calling test() method.

What I am not able to understand how come Environment , ApplicationContext and ConfigurableEnvironment get Autowired (and to which bean?)

I observed that the autowired ctx gets the context which is initialise in main().

Basically not able to understand how these gets autowired by itself (and what they are set to?)

Any help in understanding this would be of great help.


回答1:


Any class that is annotated with @Configuration is also a Spring bean. That means the MainDirver is also a spring bean that will be created during creating AnnotationConfigApplicationContext.

And after the MainDirver bean is created , Spring will then inject other beans into its field if that field is annotated with @Autowird. So in this case , Environment , ApplicationContext, and ConfigurableEnvironment are all injected this MainDirver bean.

P.S. You can think that Environment , ApplicationContext, and ConfigurableEnvironment are kind of Spring infrastructure beans that must be created even though you do not define them using @Configuration , @Service , @Bean and etc.



来源:https://stackoverflow.com/questions/56409650/about-annotationconfigapplicationcontext-in-spring-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!