Spring注解驱动开发 第八节创建初始化方法与销毁方法的第二种方式

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

果然通过实现接口的这种方式也可以做到自定义初始化和销毁方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值