Ste*_*eve 17 spring yaml spring-boot
我真的想使用YAML配置进行Spring Boot,因为我发现单个文件显示我的不同配置文件中有哪些属性是活动的,这是非常可读和有用的.不幸的是,我发现设置属性application.yml可能相当脆弱.
比如使用制表符而不是空格会导致属性不存在(据我所见,没有警告),而且由于我的YAML存在一些未知问题,我经常发现我的活动配置文件没有被设置.
所以我想知道是否有任何钩子可以让我掌握当前活动的配置文件和属性,以便我可以记录它们.
同样,如果application.yml包含错误,是否有办法导致启动失败?要么我自己验证YAML,要么我可以杀死启动过程.
我有同样的问题,并希望有一个调试标志,告诉配置文件处理系统吐出一些有用的日志记录.一种可行的方法是为应用程序上下文注册事件侦听器,并从环境中打印出配置文件.我自己也没试过这样做,所以你的里程可能会有所不同.我想也许就像这里概述的那样:
然后你会在你的听众中做这样的事情:
System.out.println("Active profiles: " + Arrays.toString(ctxt.getEnvironment().getActiveProfiles()));
Run Code Online (Sandbox Code Playgroud)
也许值得尝试一下.你可能做的另一种方法是声明要在你需要打印配置文件的代码中注入环境.即:
@Component
public class SomeClass {
@Autowired
private Environment env;
...
private void dumpProfiles() {
// Print whatever needed from env here
}
}
Run Code Online (Sandbox Code Playgroud)
除了其他答案:在上下文刷新事件上记录活动属性.
Java 8
package mypackage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MapPropertySource;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Slf4j
@Component
public class AppContextEventListener {
@EventListener
public void handleContextRefreshed(ContextRefreshedEvent event) {
printActiveProperties((ConfigurableEnvironment) event.getApplicationContext().getEnvironment());
}
private void printActiveProperties(ConfigurableEnvironment env) {
System.out.println("************************* ACTIVE APP PROPERTIES ******************************");
List<MapPropertySource> propertySources = new ArrayList<>();
env.getPropertySources().forEach(it -> {
if (it instanceof MapPropertySource && it.getName().contains("applicationConfig")) {
propertySources.add((MapPropertySource) it);
}
});
propertySources.stream()
.map(propertySource -> propertySource.getSource().keySet())
.flatMap(Collection::stream)
.distinct()
.sorted()
.forEach(key -> {
try {
System.out.println(key + "=" + env.getProperty(key));
} catch (Exception e) {
log.warn("{} -> {}", key, e.getMessage());
}
});
System.out.println("******************************************************************************");
}
}
Run Code Online (Sandbox Code Playgroud)
科特林
package mypackage
import mu.KLogging
import org.springframework.context.event.ContextRefreshedEvent
import org.springframework.context.event.EventListener
import org.springframework.core.env.ConfigurableEnvironment
import org.springframework.core.env.MapPropertySource
import org.springframework.stereotype.Component
@Component
class AppContextEventListener {
companion object : KLogging()
@EventListener
fun handleContextRefreshed(event: ContextRefreshedEvent) {
printActiveProperties(event.applicationContext.environment as ConfigurableEnvironment)
}
fun printActiveProperties(env: ConfigurableEnvironment) {
println("************************* ACTIVE APP PROPERTIES ******************************")
env.propertySources
.filter { it.name.contains("applicationConfig") }
.map { it as EnumerablePropertySource<*> }
.map { it -> it.propertyNames.toList() }
.flatMap { it }
.distinctBy { it }
.sortedBy { it }
.forEach { it ->
try {
println("$it=${env.getProperty(it)}")
} catch (e: Exception) {
logger.warn("$it -> ${e.message}")
}
}
println("******************************************************************************")
}
}
Run Code Online (Sandbox Code Playgroud)
输出如:
************************* ACTIVE APP PROPERTIES ******************************
server.port=3000
spring.application.name=my-app
...
2017-12-29 13:13:32.843 WARN 36252 --- [ main] m.AppContextEventListener : spring.boot.admin.client.service-url -> Could not resolve placeholder 'management.address' in value "http://${management.address}:${server.port}"
...
spring.datasource.password=
spring.datasource.url=jdbc:postgresql://localhost/my_db?currentSchema=public
spring.datasource.username=db_user
...
******************************************************************************
Run Code Online (Sandbox Code Playgroud)
小智 7
Actuator/env服务显示属性,但不显示哪个属性值实际处于活动状态.通常,您可能希望覆盖应用程序属性
因此,您将在多个来源中拥有相同的属性和不同的值.
Snippet bellow在启动时打印活动的应用程序属性值:
@Configuration
public class PropertiesLogger {
private static final Logger log = LoggerFactory.getLogger(PropertiesLogger.class);
@Autowired
private AbstractEnvironment environment;
@PostConstruct
public void printProperties() {
log.info("**** APPLICATION PROPERTIES SOURCES ****");
Set<String> properties = new TreeSet<>();
for (PropertiesPropertySource p : findPropertiesPropertySources()) {
log.info(p.toString());
properties.addAll(Arrays.asList(p.getPropertyNames()));
}
log.info("**** APPLICATION PROPERTIES VALUES ****");
print(properties);
}
private List<PropertiesPropertySource> findPropertiesPropertySources() {
List<PropertiesPropertySource> propertiesPropertySources = new LinkedList<>();
for (PropertySource<?> propertySource : environment.getPropertySources()) {
if (propertySource instanceof PropertiesPropertySource) {
propertiesPropertySources.add((PropertiesPropertySource) propertySource);
}
}
return propertiesPropertySources;
}
private void print(Set<String> properties) {
for (String propertyName : properties) {
log.info("{}={}", propertyName, environment.getProperty(propertyName));
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果application.yml包含错误,将导致启动失败。我想这取决于你所说的“错误”是什么意思。如果 YAML 格式不正确,它肯定会失败。此外,如果您正在设置@ConfigurationProperties标记为ignoreInvalidFields=true例如,或者如果您设置了无法转换的值。这是一个相当广泛的错误。
活动配置文件可能会在启动时通过实现进行记录Environment(但在任何情况下,您都可以轻松获取它并将其记录到您的启动器代码中 - 我认为该配置文件toString()将Environment列出活动配置文件)。如果添加执行器,活动配置文件(以及更多)也可以在 /env 端点中使用。
| 归档时间: |
|
| 查看次数: |
19446 次 |
| 最近记录: |