Skip to main content
 首页 » 编程设计

Spring启动时运行自定义业务

2022年07月19日140落叶

在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实例化过程的方式。


本文参考链接:https://blog.csdn.net/neweastsun/article/details/115491393