Spring注解驱动开发 第八节创建初始化方法与销毁方法的第二种方式
上一节我们采用initMethod与destoryMethod的方式来指定初始化和销毁方法。现在我们采用另一种方式创建。
@Component
public class black implements InitializingBean,DisposableBean {
public black(){
System.out.println("black构造器被调用了....");
}
public void destroy() throws Exception {
System.out.println("black destroy ...");
}
public void afterPropertiesSet() throws Exception {
System.out.println("black afterPropertiesSet ...");
}
}
创建一个black类实现了InitializingBean与DisposableBean 两个接口,重写destroy与afterPropertiesSet两个方法,外加一个空构造。
@Configuration
@ComponentScan("com.meng.pojo")
public class MainConfig4 {
// @Bean
// public MyBeanFactory beanFactory(){
// return new MyBeanFactory();
// }
//@Scope("prototype")
@Bean(initMethod = "init",destroyMethod = "destory")
public Blue blue(){
return new Blue();
}
}
然后在配置类中,我们用扫描包的方式注入spring容器,查看打印结果:
四月 23, 2019 2:34:13 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext prepareRefresh
信息: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 14:34:13 GMT+08:00 2019]; root of context hierarchy
black构造器被调用了....
black afterPropertiesSet ...
Blue被加载到spring容器中了...
Blue init...
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
mainConfig4
black
blue
Blue destory...
black destroy ...
四月 23, 2019 2:34:13 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@2f410acf: startup date [Tue Apr 23 14:34:13 GMT+08:00 2019]; root of context hierarchy
Process finished with exit code 0
果然通过实现接口的这种方式也可以做到自定义初始化和销毁方法。