spring 中bean 实现初始化和销毁bean之前后进行的操作的3种方法

版权声明:本文为博主原创文章,未经博主允许不得转载,如需帮助请qq联系1016258579,或者关注公众号 程序员日常锦集 ” 。 https://blog.csdn.net/weixin_38361347/article/details/89077055

spring 中bean 实现初始化和销毁bean之前进行的操作的3种方法

第一种: 通过jsr-250规范提供的注解@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作

第二种: 通过 在xml中定义init-method 和 destory-method方法(或者注解方式)

第三种: 通过bean实现spring提供的 InitializingBean和 DisposableBean接口

新建User类

public class User implements InitializingBean, DisposableBean {

    public void afterPropertiesSet() throws Exception {
        System.out.println("=========afterPropertiesSet=====");//创建之前
    }

    @Override
    public void destroy() throws Exception {
        System.out.println("=========destroy=====");//销毁
    }

}

public class User1  {

    public void afterPropertiesSet() throws Exception {
        System.out.println("=========afterPropertiesSet=====");//创建之前
    }


    public void destroy() throws Exception {
        System.out.println("=========destroy=====");//销毁
    }

}
public class User2 {

    @PostConstruct
    public void afterPropertiesSet() throws Exception {
        System.out.println("=========afterPropertiesSet=====");//创建之前
    }

    @PreDestroy
    public void destroy() throws Exception {
        System.out.println("=========destroy=====");//销毁
    }

}

配置类

/**
 * @description: bean装配
 * @author: Administrator
 * @create: 2019-04-07 21:06
 **/
@Configuration
public class Config {

    @Bean(name = "b1")
    public User user(){
        return new User();
    }

    @Bean(name = "user1",initMethod = "afterPropertiesSet",destroyMethod = "destroy")
    public User1 User1(){
        return new User1();
    }

    @Bean
    public User2 user2(){
        return new User2();
    }

}

测试类

public class Test {


    public static void main(String[] args)  {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
        System.out.println(context.getBean("b1"));
        System.out.println(context.getBean("user1"));
        System.out.println(context.getBean("user2"));
        context.close();
    }
}

结果

=====afterPropertiesSet=
=====afterPropertiesSet=
=====afterPropertiesSet=
udema.springBean.User@3d5c822d
udema.springBean.User1@6f46426d
udema.springBean.User2@73700b80

=====destroy=
=====destroy=
=====destroy=

猜你喜欢

转载自blog.csdn.net/weixin_38361347/article/details/89077055