BeanFactory是Spring底层IOC容器;
ApplicationContext是具备应用特性的BeanFactory超集;
public class DependencyInjectionDemo {public static void main(String[] args) {// 配置 XML 配置文件// 启动 Spring 应用上下文
// BeanFactory beanFactory = new ClassPathXmlApplicationContext
// ("classpath:META-INF/dependency-injection-context.xml");ApplicationContext applicationContext= new ClassPathXmlApplicationContext("classpath:META-INF/dependency-injection-context.xml");// 依赖来源一:自定义 BeanUserRepository userRepository = applicationContext.getBean("userRepository", UserRepository.class);
// System.out.println(userRepository.getUsers());whoIsIocContainer(userRepository, applicationContext);// 依赖来源二:依赖注入(内建依赖)-> DefaultListableBeanFactorySystem.out.println(userRepository.getBeanFactory());ObjectFactory<ApplicationContext> userObjectFactory = userRepository.getObjectFactory();// ApplicationContextSystem.out.println(userObjectFactory.getObject());// trueSystem.out.println("内建 Bean 对象:" + (userObjectFactory.getObject() == applicationContext));// 依赖查找 (错误)
// System.out.println(applicationContext
// .getBean(BeanFactory.class));// 依赖来源三:容器内建 BeanEnvironment environment = applicationContext.getBean(Environment.class);System.out.println("获取 Environment 类型的 Bean:" + environment);}private static void whoIsIocContainer(UserRepository userRepository,ApplicationContext applicationContext) {// ConfigurableApplicationContext <- ApplicationContext <- BeanFactory// ConfigurableApplicationContext#getBeanFactory()// 这个表达式为什么会不成立// 因为 AbstractRefreshableApplicationContext创建了DefaultListableBeanFactory,他们俩个并不是一个对象// falseSystem.out.println("内建非 Bean 对象(依赖): " + (userRepository.getBeanFactory() == applicationContext));// ApplicationContext is BeanFactory}}
执行结果:
内建非 Bean 对象(依赖): false
org.springframework.beans.factory.support.DefaultListableBeanFactory@124c278f: defining beans [user,superUser,objectFactory,userRepository]; root of factory hierarchy
org.springframework.context.support.ClassPathXmlApplicationContext@6fb554cc, started on Thu Oct 08 17:01:25 CST 2020
内建 Bean 对象:true
获取 Environment 类型的 Bean:StandardEnvironment {activeProfiles=[], defaultProfiles=[default], propertySources=[PropertiesPropertySource {name='systemProperties'}, SystemEnvironmentPropertySource {name='systemEnvironment'}]}