侧边栏壁纸
博主头像
丛庆

没事儿写代码,有事写代码。email:1024@cong.zone

  • 累计撰写 116 篇文章
  • 累计创建 97 个标签
  • 累计收到 4 条评论

【Spring】盘点spring的初始化和销毁方式

丛庆
2019-12-10 / 0 评论 / 0 点赞 / 417 阅读 / 2,212 字 / 正在检测是否收录...
温馨提示:
部分资料和图片来源于网络,如有危害到您的利益请与我联系删除,1024@cong.zone。

初始化

方式一 @PostConstruct

在Bean的方法上使用@PostConstruct注解

方式二 afterPropertiesSet()方法

实现InitializingBean接口重写afterPropertiesSet方法

方式三 在@Bean的属性中指定方法名

@Bean(initMethod = “初始化方法名”)

案例

创建一个具有多种方式初始化的Bean

public class InitDemoBean implements InitializingBean, BeanNameAware {

    @PostConstruct
    public void init1() {
        System.out.println("初始化1->@PostConstruct");
    }

    @Override
    public void setBeanName(String s) {
        System.out.println("BeanNameAware执行");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化2->InitializingBean接口,afterPropertiesSet()方法实现");
    }

    public void initMethod() {
        System.out.println("初始化3->@Bean initMethod属性指定方法名");
    }
    
}
``

创建Springboot程序
```java
@SpringBootApplication
public class InitDemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(InitDemoApplication.class, args);
        context.close();
    }

    @Bean(initMethod = "initMethod")
    public InitDemoBean initDemoBean() {
        return new InitDemoBean();
    }
}

执行结果

BeanNameAware执行
初始化1->@PostConstruct
初始化2->InitializingBean接口,afterPropertiesSet()方法实现
初始化3->@Bean initMethod属性指定方法名

总结

@PostConstruct > InitializingBean接口,afterPropertiesSet()方法实现 > @Bean initMethod属性指定方法名

销毁

方式一 @PreDestroy注解

在方法上使用@PreDestroy注解

方式二 destroy()方法

实现DisposableBean接口 重写

方式三 在@Bean的属性中指定方法名

@Bean(destroyMethod = “销毁方法名”)

案例

创建一个具有多种方式销毁的Bean

public class DestroyDemoBean implements DisposableBean {

    @PreDestroy
    public void destroy1() {
        System.out.println("销毁1->@PreDestroy");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("销毁2->DisposableBean接口实现 destroy()方法");

    }

    public void destroyMethod() {
        System.out.println("销毁3->@Bean destroyMethod属性指定方法名");
    }
}
``

创建Springboot程序
```java
@SpringBootApplication
public class DestroyDemoApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(DestroyDemoApplication.class, args);
        context.close();
    }

    @Bean(destroyMethod = "destroyMethod")
    public DestroyDemoBean destroyDemoBean() {
        return new DestroyDemoBean();
    }
}

执行结果

销毁1->@PreDestroy
销毁2->DisposableBean接口实现 destroy()方法
销毁3->@Bean destroyMethod属性指定方法名

总结

@PreDestroy > DisposableBean接口实现 destroy()方法 > @Bean destroyMethod属性指定方法名

0

评论区