Springboot 自定义Bean生命周期的另一种方式(实现InitializingBean, DisposableBean接口)

上一篇博客,我们讲解了如何通过设置@Bean的参数来定制Bean的生命周期。这篇博客,我们来让Bean的类实现InitializingBean,和DisposableBean接口来定制Bean的生命周期。

  • 实现InitializingBean,和DisposableBean接口的类:
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

public class College implements InitializingBean, DisposableBean {
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("Initial method is calling.");
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("Destroyed method is calling.");
    }
}
  • 通过@Bean注解注入Bean
import com.michael.annotation.demo.POJO.College;
import org.springframework.context.annotation.*;

@Configuration
public class MyConfig {

    @Scope("singleton")//这里可以不写,Bean默认为单例
    @Bean("St Andrews")
    public College college(){
        System.out.println("The Bean is created.");
        return new College();
    }
}
  • 测试代码:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

import static java.lang.System.out;
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
        out.println("The container has been initialized.");
         for(String name : applicationContext.getBeanDefinitionNames()){
             if(!name.contains("."))
                out.println(name);
        }
        out.println("The container has been destroyed.");
    }
}
  • 输出:
The Bean is created.
Initial method is calling.
2020-03-24 18:32:22.375  INFO 24519 --- [           main] c.m.annotation.demo.DemoApplication      : Started DemoApplication in 0.611 seconds (JVM running for 0.903)
The container has been initialized.
demoApplication
test
myConfig
personService
St Andrews
propertySourcesPlaceholderConfigurer
taskExecutorBuilder
applicationTaskExecutor
taskSchedulerBuilder
The container has been destroyed.
Destroyed method is calling.
  • 输出结果和上篇博客使用设置@Bean参数的方法得到的结果一样。其实我们可以根据实际需求,单独实现这两个接口;从这一点来看,Spring设计的代码复用性和灵活性非常明显,推测该功能应该是由Java反射和AOP实现的。
发布了80 篇原创文章 · 获赞 4 · 访问量 3775
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 鲸 设计师: meimeiellie

分享到微信朋友圈

×

扫一扫,手机浏览