美文网首页
Spring的bean声明周期

Spring的bean声明周期

作者: 匿名wm | 来源:发表于2019-04-21 17:57 被阅读0次

    启动容器时步骤:

    ->静态方法或静态代码块

    ->构造器或Setter等注入方法

    ->自动注入(Autowired)

    ->自定义实现BeanPostProcessor接口(针对所有bean都会处理)的postProcessBeforeInitialization()方法

    ->@PostConstruct注解修饰的非静态void方法

    ->实现InitializingBean接口的的afterPropertiesSet()方法(只有实现该接口的bean才会调用)

    ->bean中自定义的init-method方法(springmvc一般在xml配置bean时,使用init-method属性指定方法;springboot在类定义时使用initMethod="init",destroyMethod="destory"注解指定,比如:@Bean(name="robotStore",initMethod="init",destroyMethod="destory")

    ->自定义实现BeanPostProcessor接口(针对所有bean都会处理)的postProcessAfterInitialization()方法

    关闭容器时步骤

    ->@PreDestroy注解修饰的非静态void方法

    ->DisposableBean的destroy()

    ->bean中自定义的的destroy-method方法,定义方法见init-method说明

    注:

    @Bean在SpringBoot中使用时,是方法级别的注解,一般放在@Configuration修饰的类中使用,比如:

    @Configuration

    public class MyBean {

        @Bean(name ="myService",initMethod ="initMethod",destroyMethod ="destoryMethod")

    public MyService myService(){

    return new MyServiceImpl();

        }

    }

    此处会生成一个name=myService的bean,同时设置了自定义初始化和销毁的方法

    等同于xml配置的

    <beans>

        <bean name="myService" class="com.test.MyServiceImpl" init-method = "initMethod" destory-method="destoryMethod"/>

    </beans>

    相关文章

      网友评论

          本文标题:Spring的bean声明周期

          本文链接:https://www.haomeiwen.com/subject/nkujgqtx.html