梳理SpringBean的生命周期

demo

public class Source {

    /**
     * 类型
     */
    private String fruit;

    /**
     * 糖分描述
     */
    private  String sugar;

    /**
     * 大小杯
     */
    private String size;

    public String getFruit() {
        return fruit;
    }

    public void setFruit(String fruit) {
        this.fruit = fruit;
    }

    public String getSugar() {
        return sugar;
    }

    public void setSugar(String sugar) {
        this.sugar = sugar;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }
}

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.*;
import org.springframework.context.*;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.StringValueResolver;

/**
 * 其他的接口只针对单一bean, 代码顺序就是实际的执行顺序
 */
@Component
public class JuiceMark2 implements BeanNameAware, BeanClassLoaderAware, BeanFactoryAware, ApplicationContextAware, EnvironmentAware, InitializingBean, EmbeddedValueResolverAware, ApplicationEventPublisherAware, ResourceLoaderAware, MessageSourceAware {

    private String beverageShop = null;

    private Source source = null;

    // ---------------------根据源码逻辑分类, Aware类型的接口Group1
    @Override
    public void setBeanName(String s) {
        System.out.println(String.format("[%s]调用BeanNameAware接口的setBeanName方法", this.getClass().getSimpleName()));
    }

    @Override
    public void setBeanClassLoader(ClassLoader classLoader) {
        System.out.println(String.format("[%s]调用BeanClassLoaderAware接口的setBeanClassLoader方法", this.getClass().getSimpleName()));
    }

    @Override
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
        System.out.println(String.format("[%s]调用BeanFactoryAware接口的setBeanFactory方法", this.getClass().getSimpleName()));
    }

    // ---------------------Aware类型的接口Group2

    @Override
    public void setEnvironment(Environment environment) {
        System.out.println(String.format("[%s]调用EnvironmentAware接口的setEnvironment方法", this.getClass().getSimpleName()));
    }

    /**
     * 实现该接口能够获取Spring EL解析器,用户的自定义注解需要支持spel表达式的时候可以使用
     *
     * @param stringValueResolver
     */
    @Override
    public void setEmbeddedValueResolver(StringValueResolver stringValueResolver) {
        System.out.println(String.format("[%s]调用EmbeddedValueResolverAware接口的setEmbeddedValueResolver方法", this.getClass().getSimpleName()));
    }

    @Override
    public void setResourceLoader(ResourceLoader resourceLoader) {
        System.out.println(String.format("[%s]调用ResourceLoaderAware接口的setResourceLoader方法", this.getClass().getSimpleName()));
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        System.out.println(String.format("[%s]调用ApplicationEventPublisherAware接口的setApplicationEventPublisher方法", this.getClass().getSimpleName()));
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        System.out.println(String.format("[%s]调用MessageSourceAware接口的setMessageSource方法", this.getClass().getSimpleName()));
    }

    /**
     * 要求ioc容器实现ApplicationContext接口
     *
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println(String.format("[%s]调用ApplicationContextAware接口的setApplicationContext方法", this.getClass().getSimpleName()));
    }

    // --------------------------------------------------- 生命周期接口

    // 针对全部bean的BeanPostProcessor.postProcessBeforeInitialization

    /**
     * 针对单个bean的 InitializingBean.afterPropertiesSet
     *
     * @throws Exception
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(String.format("[%s]调用InitializingBean接口的afterPropertiesSet方法", this.getClass().getSimpleName()));
    }

    /**
     * 自定义初始化方法
     */
    public void init() {
        System.out.println(String.format("[%s]执行自定义初始化方法", this.getClass().getSimpleName()));
    }

    // 针对全部bean的BeanPostProcessor.postProcessAfterInitialization

    // 针对ioc容器的 DisposableBean.destroy

    /**
     * 自定义销毁方法
     */
    public void destroy() {
        System.out.println(String.format("[%s]执行自定义销毁方法", this.getClass().getSimpleName()));
    }

    public String getBeverageShop() {
        return beverageShop;
    }

    public void setBeverageShop(String beverageShop) {
        this.beverageShop = beverageShop;
    }

    public Source getSource() {
        return source;
    }

    public void setSource(Source source) {
        this.source = source;
    }

}

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 针对所有bean
 */
@Component
public class BeanPostProcessorImpl implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(String.format("[%s]调用BeanPostProcessor接口的postProcessBeforeInitialization方法, 开始实例化", bean.getClass().getSimpleName()));
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        System.out.println(String.format("[%s]调用BeanPostProcessor接口的postProcessAfterInitialization方法, 实例化完成", bean.getClass().getSimpleName()));
        return bean;
    }
}

import org.springframework.beans.factory.DisposableBean;
import org.springframework.stereotype.Component;

/**
 * 针对ioc容器销毁的
 */
@Component
public class DisposableBeanImpl implements DisposableBean {

    @Override
    public void destroy() throws Exception {
        System.out.println("调用接口DisposableBean的destroy方法");
    }
}

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.context.annotation.Bean;

/**
 * Hello world!
 */
@SpringBootApplication
@EnableEurekaServer
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
        System.out.println("Hello World!");
    }

    @Bean
    public Source source(){
        Source source = new Source();
        source.setFruit("橙汁");
        source.setSugar("少糖");
        source.setSize("大杯");
        return source;
    }

    @Bean(initMethod = "init", destroyMethod = "destroy")
    public JuiceMark2 juiceMark2(@Autowired Source source){
        JuiceMark2 juiceMark2 = new JuiceMark2();
        juiceMark2.setBeverageShop("贡茶");
        juiceMark2.setSource(source);
        return juiceMark2;
    }
}

实现结果

梳理SpringBean的生命周期_第1张图片
梳理SpringBean的生命周期_第2张图片

总结

  • 生命周期: 实例化 -> 属性赋值 -> 初始化 -> 销毁
    createBeanInstance() -> 实例化
    populateBean() -> 属性赋值
    initializeBean() -> 初始化
  • 实例化和属性赋值对应构造方法和setter方法的注入,初始化和销毁是用户能自定义扩展的两个阶段。
  • DisposableBean针对ioc容器
  • 其他的接口只针对单一bean
  • BeanPostProcessor针对全部bean
  • 关于BeanPostProcessor执行顺序与两个排序接口相关:PriorityOrdered和Ordered, 返回值越低优先级越高. 实现PriorityOrdered的首先被执行, 实现Ordered的然后执行, 都没有实现的最后执行

你可能感兴趣的:(spring,spring,ioc)