使用Spring启动时运行自定义业务

 更新时间:2021年07月22日 14:41:03   作者:梦想画家  
这篇文章主要介绍了使用Spring启动时运行自定义业务的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

在Spring应用启动时运行自定义业务的场景很常见,但应用不当也可能会导致一些问题。

基于Spring控制反转(Inverse of Control)功能用户几乎不用干预bean实例化过程,对于自定义业务则需要控制部分流程及容器,因此值得须特别关注。

1. Spring启动时运行自定义业务

我们不能简单包括自定义业务在bean的构造函数或在实例化任何对象之后调用方法,这些过程不由我们控制。请看示例:

@Component
public class InvalidInitExampleBean {
    @Autowired
    private Environment env;
    public InvalidInitExampleBean() {
        env.getActiveProfiles();
    }
}

这里尝试在构造函数中访问自动装配的属性。当调用构造函数时,Spring bean仍没有全部初始化,因此导致NullPointerExceptions异常。下面介绍几种方式解决此问题。

1.1 @PostConstruct 注解

@PostConstruct注解用于方法上,实现bean初始化后立刻执行一次。需要注意的是,即使没有对象注入,Spring也会执行注解方法。

@Component
public class PostConstructExampleBean {
    private static final Logger LOG 
      = Logger.getLogger(PostConstructExampleBean.class);
    @Autowired
    private Environment environment;
    @PostConstruct
    public void init() {
        LOG.info(Arrays.asList(environment.getDefaultProfiles()));
    }
}

上面示例可以实现Environment environment被安全注入,然后调用注解方法且不会出现空指针异常。

1.2 InitializingBean 接口

InitializingBean接口实现功能与上节类似。但需要实现接口并重写afterPropertiesSet方法。

下面重写前节的示例:

@Component
public class InitializingBeanExampleBean implements InitializingBean {
    private static final Logger LOG 
      = Logger.getLogger(InitializingBeanExampleBean.class);
    @Autowired
    private Environment environment;
    @Override
    public void afterPropertiesSet() throws Exception {
        LOG.info(Arrays.asList(environment.getDefaultProfiles()));
    }
}

1.3 ApplicationListener 监听器

该方法可用于在Spring上下文初始化之后执行自定义业务。因此不针对特定bean,而是等待所有bean初始化之后。应用时需要实现ApplicationListener接口:

@Component
public class StartupApplicationListenerExample implements 
  ApplicationListener<ContextRefreshedEvent> {
    private static final Logger LOG 
      = Logger.getLogger(StartupApplicationListenerExample.class);
    public static int counter;
    @Override public void onApplicationEvent(ContextRefreshedEvent event) {
        LOG.info("Increment counter");
        counter++;
    }
}

同样可以引入@EventListener注解实现:

@Component
public class EventListenerExampleBean {
    private static final Logger LOG 
      = Logger.getLogger(EventListenerExampleBean.class);
    public static int counter;
    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        LOG.info("Increment counter");
        counter++;
    }
}

上面示例使用ContextRefreshedEvent,具体选择哪种事件根据你的业务需要。

1.4 @Bean的初始化方法

该注解的initMethod属性可用于在bean初始化之后执行方法,示例:

public class InitMethodExampleBean {
    private static final Logger LOG = Logger.getLogger(InitMethodExampleBean.class);
    @Autowired
    private Environment environment;
    public void init() {
        LOG.info(Arrays.asList(environment.getDefaultProfiles()));
    }
}

既不要实现接口,也不要特定注解。通过注解定义Bean:

@Bean(initMethod="init")
public InitMethodExampleBean initMethodExampleBean() {
    return new InitMethodExampleBean();
}

对应xml配置:

<bean id="initMethodExampleBean"
  class="com.baeldung.startup.InitMethodExampleBean"
  init-method="init">
</bean>

1.5 构造函数注入

如果使用构造器注入属性,可以简单地在构造函数中包括业务:

@Component 
public class LogicInConstructorExampleBean {
    private static final Logger LOG 
      = Logger.getLogger(LogicInConstructorExampleBean.class);
    private final Environment environment;
    @Autowired
    public LogicInConstructorExampleBean(Environment environment) {
        this.environment = environment;
        LOG.info(Arrays.asList(environment.getDefaultProfiles()));
    }
}

1.6 Spring Boot CommandLineRunner接口

Spring Boot 提供了CommandLineRunner接口,重写run方法,可以在应用启动时Spring应用上下文实例化之后调用。

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {
    private static final Logger LOG =
      LoggerFactory.getLogger(CommandLineAppStartupRunner.class);
    public static int counter;
    @Override
    public void run(String...args) throws Exception {
        LOG.info("Increment counter");
        counter++;
    }
}

CommandLineRunner bean在相同上下文中可以定义多个,通过使用Ordered 接口或@Ordere注解确定顺序。

1.7 Spring Boot ApplicationRunner

与CommandLineRunner类似,Spring Boot 也提供了ApplicationRunner接口,重写run方法可以实现应用启动时执行自定义业务。另外其回调方法没有使用String参数,而是使用ApplicationArguments类的实例。

ApplicationArguments有方法可以获取可选参数及普通参数的值,参数前有–的表示可选参数。

@Component
public class AppStartupRunner implements ApplicationRunner {
    private static final Logger LOG =
      LoggerFactory.getLogger(AppStartupRunner.class);
    public static int counter;
    @Override
    public void run(ApplicationArguments args) throws Exception {
        LOG.info("Application started with option names : {}", 
          args.getOptionNames());
        LOG.info("Increment counter");
        counter++;
    }
}

2. 执行顺序

多种方法对bean同时进行控制,对应执行顺序如下:

  1. 构造函数
  2. @PostConstruct注解方法
  3. InitializingBean的afterPropertiesSet()
  4. @Bean或xml中标注的初始化方法

读者可以自行测试进行验证。

3. 总结

本文介绍多种方式实现在Spring启动时实现自定义业务。通过对比不同方式实现加深对Spring的理解,掌握更多控制bean实例化过程的方式。以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • RocketMq事务消息发送代码流程详解

    RocketMq事务消息发送代码流程详解

    这篇文章主要介绍了RocketMq事务消息发送代码流程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-07-07
  • Java 数组高频考点分析讲解

    Java 数组高频考点分析讲解

    数组对于每一门编程语言来说都是重要的数据结构之一,当然不同语言对数组的实现及处理也不尽相同。Java 语言中提供的数组是用来存储固定大小的同类型元素
    2022-04-04
  • 如何将Tomcat容器替换为Jetty容器

    如何将Tomcat容器替换为Jetty容器

    这篇文章主要介绍了如何将Tomcat容器替换为Jetty容器问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2025-03-03
  • Java后台实现浏览器一键导出下载zip压缩包

    Java后台实现浏览器一键导出下载zip压缩包

    这篇文章主要为大家详细介绍了Java后台实现浏览器一键导出下载zip压缩包,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-07-07
  • Spring Boot @Async 异步任务执行方法

    Spring Boot @Async 异步任务执行方法

    本篇文章主要介绍了Spring Boot @Async 异步任务执行方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • 详解spring cloud hystrix请求缓存(request cache)

    详解spring cloud hystrix请求缓存(request cache)

    这篇文章主要介绍了详解spring cloud hystrix请求缓存(request cache),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • Java中的Random和ThreadLocalRandom详细解析

    Java中的Random和ThreadLocalRandom详细解析

    这篇文章主要介绍了Java中的Random和ThreadLocalRandom详细解析,Random 类用于生成伪随机数的流, 该类使用48位种子,其使用线性同余公式进行修改,需要的朋友可以参考下
    2024-01-01
  • 详解Thymeleaf的三种循环遍历方式

    详解Thymeleaf的三种循环遍历方式

    Thymeleaf 是一款用于渲染 XML/XHTML/HTML5 内容的模板引擎。本文为大家总结了Thymeleaf的三种循环遍历方式,感兴趣的可以跟随小编一起学习一下
    2022-06-06
  • Java中数组在内存中存放原理的讲解

    Java中数组在内存中存放原理的讲解

    今天小编就为大家分享一篇关于Java中数组在内存中存放原理的讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-04-04
  • spring boot 静态资源处理方法

    spring boot 静态资源处理方法

    本篇文章主要介绍了spring boot 静态资源处理方法。小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-03-03

最新评论