Spring Boot 配置启动初始化参数或资源的几种方式
原创2020/9/2大约 2 分钟
Spring Boot 配置启动初始化参数或资源的几种方式
1、利用属性参数资源
1.1、配置文件参数映射的时候初始化资源
属性实体:
public class DemoProperties {
private String appId;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
}配置自动映射(还有其他实现方式,不再列举):
@Configuration
public class DemoConfig {
@Bean
@ConfigurationProperties(prefix = "demo")
public DemoProperties demoProperties() {
DemoProperties prop = new DemoProperties();
System.out.println("【DemoConfig】-------------->执行了:" + prop.getAppId());
// do something else...
return prop;
}
}2、利用初始化方法
2.1、使用注解 @PostConstruct
相当于 Spring 中传统的 init-method 方式
@Configuration
public class PostConstructConfig {
@Autowired
private DemoProperties properties;
@PostConstruct
public void init() {
System.out.println("【PostConstructConfig】-------------->执行了:" + properties.getAppId());
}
}3、利用启动接口
3.1、实现 ApplicationRunner 接口
@Component
public class MyApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("【MyApplicationRunner】-------------->执行了");
}
}3.2、实现 CommandLineRunner 接口
@Component
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("【MyCommandLineRunner】-------------->执行了");
}
}注:
- 这两个接口工作方式相同,都只提供单一的 run 方法,而且该方法仅在 SpringApplication.run(...)完成之前调用,更准确的说是在构造 SpringApplication 实例完成之后调用 run()的时候;
- ApplicationRunner 执行早于 CommandLineRunner。
- 可以使用 @Order 注解指定执行顺序
- CommandLineRunner 的参数是最原始的参数,没有进行任何处理;ApplicationRunner 的参数做了进一步封装;参考 https://juejin.im/post/6844903657989734414
4、利用事件监听机制
4.1、实现ApplicationListener接口
@Component
public class StartedListenerByInterface implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("【StartedListenerByInterface】-------------->执行了");
}
}4.2、使用 @EventListener 注解
@Component
public class StartedListenerByAnnotation {
@EventListener
public void onApplicationEvent(ApplicationReadyEvent event) {
System.out.println("【StartedListenerByAnnotation】-------------->执行了");
}
}注:还有很多其他的事件可以使用,如:ApplicationStartedEvent 等,结合场景自行搭配。另外,事件机制有时候会出现调用多次的情况,可能是 bean 被 spring 扫描了多次或其他原因,自行百度。
5、测试
把这些方式都写上,最终的输出结果为:
【DemoConfig】-------------->执行了:null
【PostConstructConfig】-------------->执行了:afdfafdfdfdd
【MyApplicationRunner】-------------->执行了
【MyCommandLineRunner】-------------->执行了
【StartedListenerByAnnotation】-------------->执行了
【StartedListenerByInterface】-------------->执行了对于 2、3、4、5、6 方式,都可以 @Autowired 其他属性来使用。

