java - 在 Spring Boot 应用程序初始化之前读取属性
问题描述
我有一种情况,在运行 spring 应用程序之前读取classpath:app.properties
或classpath:presentation-api.properties
使用属性会很有用,以便设置几个遗留配置文件。
所以它会是这样的:
@SpringBootApplication
@PropertySource({"classpath:app.properties", "classpath:various_other.properties"})
public class MainApp extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
boolean legacyPropertyA = // might be set in classpath:app.properties or classpath:various_other.properties or not at all
boolean legacyPropertyB = // might be set in classpath:app.properties or classpath:various_other.properties or not at all
if (legacyPropertyA) {
builder.profiles("legacyProfileA");
}
if (legacyPropertyB) {
builder.profiles("legacyProfileB");
}
return super.configure(builder);
}
}
legacyPropertyA
检索和的最干净的方法是legacyPropertyB
什么?
解决方案
我认为您可以结合@Value和@PostConstruct注释以获得更清洁的解决方案。请看下面的例子:
@SpringBootApplication
@PropertySource({"classpath:application-one.properties", "classpath:application-two.properties"})
public class MyApplication extends SpringBootServletInitializer {
@Value("${property.one}")
private String propertyOne;
@Value("${property.two}")
private String propertyTwo;
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(MyApplication.class);
}
@PostConstruct
public void initProperties() {
System.out.println(propertyOne);
System.out.println(propertyTwo);
}
}
我希望这可以帮助你。请让我知道您有任何问题。
推荐阅读
- c# - 尝试访问 Azure Function 时出错
- sql - .NET 多行 SQL 插入支持基于集合的操作
- java - 如何创建地图
> java 8 单流? - vue.js - 如何在纯 js 文件中编写 vue 组件?[没有构建和 webpack 的 Vue.js]
- php - Symfony Finder - ““1”目录不存在f
- ruby - Ruby 并排错误 (sxstrace)
- php - 使用 Zend 或 Composer 在 PHP 中自动加载是如何工作的?
- ssl - SSL - 升级到 TLSv1.3 的问题
- sql - SQL 始终加密 CMK 证书存储最佳实践
- javascript - JavaScript - Chrome 打开新窗口,音频自动播放