【发布时间】:2019-06-01 19:06:55
【问题描述】:
我写了以下简单的独立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);
}
}
我知道在 main() 中我们正在创建一个新的应用程序上下文,然后创建 Bean 并最终调用 test() 方法。
我无法理解为什么 Environment 、 ApplicationContext 和 ConfigurableEnvironment 会自动连接(以及到哪个 bean?)
我观察到自动连接的ctx 获得了在 main() 中初始化的上下文。
基本上无法理解这些是如何自行自动装配的(以及它们的设置是什么?)
对理解这一点的任何帮助都会有很大帮助。
【问题讨论】:
标签: java spring spring-ioc