飞机票:黑马程序员Spring视频教程
一、BeanFactory以及ApplicationContext-
Spring核心容器
- Spring的两个核心容器BeanFactory、ApplicationContext
- ApplicationContext是BeanFactory的补充,本质上来说是对BeanFactory的功能进行组合以及扩展从而补充其他内容例如,国际化能力(MessageSource)、获取资源的能力(getResource)、事件发布能力(Event Publish)等
1.1 启动一个空的MAVEN项目
1.2 引入spring-boot依赖(pom.xml)
PS:这里使用Lombok 如果出现编译错误请百度Lombok的用法 安装指定插件
4.0.0 org.example demo 1.0-SNAPSHOT spring-boot-parent org.springframework.boot 2.6.7 8 8 UTF-8 org.springframework.boot spring-boot-starter-logging org.springframework.boot spring-boot-autoconfigure org.projectlombok lombok 1.3 在resources下创建 application.properties、message.properties、message_en.properties、message_zh.properties
- 编辑message_en.properties
hi=hello
- 编辑message_zh.properties
hi=你好
1.4 创建两个Bean组件
@Component public class Component1 { @EventListener public void aaa(UserRegisteredEvent event) { System.out.println(event); } } @Component public class Component2 { }1.5 新建启动类 并感受
@SpringBootApplication public class A01Application { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException { final ConfigurableApplicationContext context = SpringApplication.run(A01Application.class, args); final Field singletonObjects = DefaultSingletonBeanRegistry.class.getDeclaredField("singletonObjects"); singletonObjects.setAccessible(true); final ConfigurableListableBeanFactory beanFactory = context.getBeanFactory(); Mapmap = (Map ) singletonObjects.get(beanFactory); map.entrySet().stream().filter(entry -> entry.getKey().startsWith("component")) .forEach(entry -> System.out.println(entry.getKey() + "=" + entry.getValue())); System.out.println(context.getMessage("hi", null, Locale.CHINA)); System.out.println(context.getMessage("hi", null, Locale.ENGLISH)); // final Resource[] resources = context.getResources("classpath:application.properties"); final Resource[] resources = context.getResources("classpath*:META-INF/spring.factories"); for (Resource resource : resources) { System.out.println(resource); } System.out.println(context.getEnvironment().getProperty("server.port")); context.publishEvent(new UserRegisteredEvent(context)); } } -
深入了解BeanFactory
2.1 在一个测试类TestBeanFactory中main函数开始玩耍
@Slf4j public class TestBeanFactory { public static void main(String[] args) { // 构造一个默认的BeanFactory DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // 注册Config的Bean final AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(Config.class).setScope("singleton").getBeanDefinition(); beanFactory.registerBeanDefinition("config", beanDefinition); for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } System.out.println("================"); log.info("添加注解后处理器"); // 为bean添加一些常用的后处理器 AnnotationConfigUtils.registerAnnotationConfigProcessors(beanFactory); log.info("获取并启动后处理的Bean"); beanFactory.getBeansOfType(BeanFactoryPostProcessor.class).values() .forEach(beanFactoryPostProcessor -> beanFactoryPostProcessor.postProcessBeanFactory(beanFactory)); log.info("注册其他的后处理器 例如自动注入等"); AtomicInteger counter = new AtomicInteger(); // beanFactory.getBeansOfType(BeanPostProcessor.class).values() // .forEach(beanPostProcessor -> { // log.info("序号:{},添加后处理器:{}", counter.incrementAndGet(), beanPostProcessor); // beanFactory.addBeanPostProcessor(beanPostProcessor); // }); beanFactory.getBeansOfType(BeanPostProcessor.class).values().stream() .sorted(Objects.requireNonNull(beanFactory.getDependencyComparator())) .forEach(beanPostProcessor -> { log.info("序号:{},添加后处理器:{}", counter.incrementAndGet(), beanPostProcessor); beanFactory.addBeanPostProcessor(beanPostProcessor); }); log.info("这个时候的bean工厂的bean"); for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } // 准备好所有的单例 log.info("预加载所有单例"); beanFactory.preInstantiateSingletons(); log.info("Bean1.bean2={}", beanFactory.getBean(Bean1.class).getBean2()); log.info("Bean1.bean3={}", beanFactory.getBean(Bean1.class).getBean3()); } @Configuration static class Config { @Bean public Bean1 bean1() { return new Bean1(); } @Bean public Bean2 bean2() { return new Bean2(); } @Bean public Bean3 bean3() { return new Bean3(); } @Bean public Bean4 bean4() { return new Bean4(); } } interface Inter { } static class Bean3 implements Inter { } static class Bean4 implements Inter { } static class Bean1 { public Bean1() { log.debug("Bean1构造"); } @Autowired Bean2 bean2; public Bean2 getBean2() { return bean2; } @Autowired // 在添加了 @Autowired @Resource的情况下 Autowired的优先级大于Resource的情况下 这个和后处理器的添加顺序有关 @Resource(name = "bean4") Inter bean3; public Inter getBean3() { return bean3; } } static class Bean2 { public Bean2() { log.debug("Bean2构造"); } } } -
ApplicationContext的不同玩法
- 在pom.xml 加入web依赖
org.springframework.boot spring-boot-starter-web- 不同构造ApplicationContext的方法 挨个感受
- 在resources下新建文件b01.xml
- PS:注意包路径改为自己对应的
@Slf4j public class A02Application { public static void main(String[] args) { // testClassPathXmlApplicationContext(); // testFileSystemXmlApplicationContext(); // testAnnotationConfigApplicationContext(); testAnnotationConfigServletWebServerApplicationContext(); // ApplicationContext中进行xml文件创建Bean // DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); // log.debug("读取之前。。。"); // for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) { // System.out.println(beanDefinitionName); // } // log.debug("读取之后。。。"); // XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(beanFactory); // reader.loadBeanDefinitions(new ClassPathResource("b01.xml")); // for (String beanDefinitionName : beanFactory.getBeanDefinitionNames()) { // System.out.println(beanDefinitionName); // } } // ↓ 经典容器 基于 classpath 下的 xml 格式的配置文件来创建 private static void testClassPathXmlApplicationContext() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("b01.xml"); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } System.out.println(context.getBean(Bean2.class).getBean1()); } // ↓ 基于磁盘路径下的xml 其他同上 private static void testFileSystemXmlApplicationContext() { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("file://D:\mine\learn-log\2022.06.11\spring5-source-code-learn\demo\src\main\resources\b01.xml"); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } System.out.println(context.getBean(Bean2.class).getBean1()); } // ↓ 基于注解配置创建Bean private static void testAnnotationConfigApplicationContext() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } System.out.println(context.getBean(Bean2.class).getBean1()); } // ↓ 基于注解 用于web环境 private static void testAnnotationConfigServletWebServerApplicationContext() { AnnotationConfigServletWebServerApplicationContext context = new AnnotationConfigServletWebServerApplicationContext(WebConfig.class); for (String beanDefinitionName : context.getBeanDefinitionNames()) { System.out.println(beanDefinitionName); } } @Configuration static class WebConfig { @Bean // 注册tomcat容器工厂 内嵌的Tomcat public ServletWebServerFactory servletWebServerFactory() { return new TomcatServletWebServerFactory(); } @Bean // 生成DispatcherServlet Bean public DispatcherServlet dispatcherServlet() { return new DispatcherServlet(); } @Bean // 注册DispatcherServlet public DispatcherServletRegistrationBean registrationBean(DispatcherServlet dispatcherServlet) { return new DispatcherServletRegistrationBean(dispatcherServlet, "/"); } @Bean // 写一个简单额控制器 这里的Controller是 org.springframework.web.servlet.mvc下的 // 不是 Controller 注解 public Controller controller1() { return (request, response) -> { response.getWriter().println("hello"); return null; }; } } @Configuration static class Config { @Bean public Bean1 bean1() { return new Bean1(); } @Bean public Bean2 bean2() { return new Bean2(); } } static class Bean1 { } static class Bean2 { private Bean1 bean1; public Bean1 getBean1() { return bean1; } @Autowired public void setBean1(Bean1 bean1) { this.bean1 = bean1; } } }



