服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 使用Spring启动时运行自定义业务

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

2021-10-19 10:53梦想画家 Java教程

这篇文章主要介绍了使用Spring启动时运行自定义业务的操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

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

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

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

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

?
1
2
3
4
5
6
7
8
@Component
public class InvalidInitExampleBean {
    @Autowired
    private Environment env;
    public InvalidInitExampleBean() {
        env.getActiveProfiles();
    }
}

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

1.1 @PostConstruct 注解

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

?
1
2
3
4
5
6
7
8
9
10
11
@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方法。

下面重写前节的示例:

?
1
2
3
4
5
6
7
8
9
10
11
@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接口:

?
1
2
3
4
5
6
7
8
9
10
11
@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注解实现:

?
1
2
3
4
5
6
7
8
9
10
11
@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初始化之后执行方法,示例:

?
1
2
3
4
5
6
7
8
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:

?
1
2
3
4
@Bean(initMethod="init")
public InitMethodExampleBean initMethodExampleBean() {
    return new InitMethodExampleBean();
}

对应xml配置:

?
1
2
3
4
<bean id="initMethodExampleBean"
  class="com.baeldung.startup.InitMethodExampleBean"
  init-method="init">
</bean>

1.5 构造函数注入

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

?
1
2
3
4
5
6
7
8
9
10
11
@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应用上下文实例化之后调用。

?
1
2
3
4
5
6
7
8
9
10
11
@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有方法可以获取可选参数及普通参数的值,参数前有–的表示可选参数。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
@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实例化过程的方式。以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/neweastsun/article/details/115491393

延伸 · 阅读

精彩推荐