Spring中Bean创建完成后执行指定代码的几种实现方式

栏目: Java · 发布时间: 7年前

内容简介:在实际开发中经常会遇到在spring容器加载完某个bean之后,需要执行一些业务代码的场景。比如初始化配置、缓存等。有以下几种方式可以实现此需求(欢迎补充)实现ApplicationListener接口并实现方法onApplicationEvent()方法,Bean在创建完成后会执行onApplicationEvent方法实现InitializingBean接口并实现方法afterPropertiesSet(),Bean在创建完成后会执行afterPropertiesSet()方法

在实际开发中经常会遇到在spring容器加载完某个bean之后,需要执行一些业务代码的场景。比如初始化配置、缓存等。有以下几种方式可以实现此需求(欢迎补充)

实现ApplicationListener接口

实现ApplicationListener接口并实现方法onApplicationEvent()方法,Bean在创建完成后会执行onApplicationEvent方法

@Component
public class DoByApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
    public DoByApplicationListener() {
        System.out.println("DoByApplicationListener constructor");
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event.getApplicationContext().getParent() == null) {
            System.out.println("DoByApplicationListener do something");
        }
    }
}

实现InitializingBean接口

实现InitializingBean接口并实现方法afterPropertiesSet(),Bean在创建完成后会执行afterPropertiesSet()方法

@Component
public class DoByInitializingBean implements InitializingBean {
    public DoByInitializingBean() {
        System.out.println("DoByInitializingBean constructor");
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("InitByInitializingBean do something");
    }
}

使用@PostConstruct注解

在Bean的某个方法上使用@PostConstruct注解,Bean在创建完成后会执行该方法

@Component
public class DoByPostConstructAnnotation {
    public DoByPostConstructAnnotation() {
        System.out.println("DoByPostConstructAnnotation constructor");
    }

    @PostConstruct
    public void init(){
        System.out.println("InitByPostConstructAnnotation do something");
    }
}

使用init-method

使用init-metod可以指定Bean在创建完成后,初始化使用的方法,比如有个Bike类

public class Bike {
    public Bike() {
        System.out.println("Bike constructor");
    }
    public void initBike() {
        System.out.println("Bike do something");
    }
}

使用@Configuration注解来启动容器,并设置Bike的初始化方法为initBike

@Configuration
public class DoByInitMethod {
    @Bean(initMethod ="initBike")
    public Bike bike() {
        return new Bike();
    }
}

以上方式和代码全部都测试运行过,绝对可用!


以上所述就是小编给大家介绍的《Spring中Bean创建完成后执行指定代码的几种实现方式》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

TensorFlow:实战Google深度学习框架(第2版)

TensorFlow:实战Google深度学习框架(第2版)

顾思宇、梁博文、郑泽宇 / 电子工业出版社 / 2018-2-1 / 89

TensorFlow是谷歌2015年开源的主流深度学习框架,目前已得到广泛应用。《TensorFlow:实战Google深度学习框架(第2版)》为TensorFlow入门参考书,旨在帮助读者以快速、有效的方式上手TensorFlow和深度学习。书中省略了烦琐的数学模型推导,从实际应用问题出发,通过具体的TensorFlow示例介绍如何使用深度学习解决实际问题。书中包含深度学习的入门知识和大量实践经......一起来看看 《TensorFlow:实战Google深度学习框架(第2版)》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具