Spring 源码解析(二)

32 阅读1分钟

三种context

ClassPathXmlApplicationContext

根据 xml 获取bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
​
    <!-- 定义一个Employee类型的bean -->
    <bean id="employee" class="org.example.Employee">
        <constructor-arg value="John Doe"/>
        <constructor-arg value="30"/>
    </bean></beans>

对应对象

public class Employee {
    private String name;
    private int age;
​
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
​
    public void work() {
        System.out.println(name + " is working.");
    }
}

测试

    private static void testClassPathXmlApplicationContext() {
        // 根据 xml 获取bean
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("b01.xml");
        for (String beanDefinitionName : context.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
    }
​

AnnotationConfigApplicationContext

bean

    @Configuration
    static class Config{
​
        @Bean
        public Bean1 test(){
            return new Bean1();
        }
        @Bean
        public Bean2 test2(){
            return new Bean2();
        }
    }

测试

    private static void testAnnotationConfigApplicationContext() {
        AnnotationConfigApplicationContext context3 = new AnnotationConfigApplicationContext(BeanFactoryTest.Config.class);
        for (String beanDefinitionName : context3.getBeanDefinitionNames()) {
            System.out.println(beanDefinitionName);
        }
    }

AnnotationConfigServletWebApplicationContext

Bean

@Configuration
    static class WebConfig{
        // 内嵌服务器
        @Bean
        public ServletWebServerFactory servletWebServerFactory(){
            return new TomcatServletWebServerFactory();
        }
​
        @Bean
        public DispatcherServlet dispatcherServlet(){
            return new DispatcherServlet();
        }
​
        @Bean
        public DispatcherServletRegistrationBean registrationBean( DispatcherServlet dispatcherServlet){
            return new DispatcherServletRegistrationBean(dispatcherServlet, "/");
        }
​
        @Bean("/hello")
        public Controller controller1(){
            return (request, response) -> {
                response.getWriter().print("hello");
                return null;
            };
        }
    }

测试

    private static void testAnnotationConfigServletWebApplicationContext() {
        AnnotationConfigServletWebApplicationContext context4 = new     AnnotationConfigServletWebApplicationContext(WebConfig.class);
    }
​

Bean的生命周期

用一个bean告诉你

public class LifeCycleBean {
    private static final Logger logger = LoggerFactory.getLogger(LifeCycleBean.class);
​
    private LifeCycleBean() {
        logger.info("构造");
    }
​
    @Autowired
    public void autoWire(@Value("${JAVA_HOME}") String home) {
        logger.info("依赖注入:" + home);
    }
​
    @PostConstruct
    public void init() {
        logger.info("初始化");
    }
​
    @PreDestroy
    public void destroy() {
        logger.info("销毁");
    }
}
​

启动类

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Application.class, args);
        context.close();
    }
​
}