问题
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