在启动之前在 SpringBoot 中记录 @ConfigurationProperties?
Log @ConfigurationProperties in SpringBoot prior to startup?
我正在尝试找到一种方法来在上下文启动之前记录我的应用程序属性(通过@ConfigurationProperties 注入到我的 bean 中),以便我可以在所有 bean 初始化之前看到确切的属性。
我已尝试在 ApplicationEnvironmentPreparedEvent 上创建一个侦听器,但除了一次检索一个单独的属性外,无法检索所有定义的属性。
有没有简单的方法来做到这一点?某种方法可以先初始化 @ConfigurationProperties
并记录它们的内容,或者在上下文创建之前检索所有应用程序启动属性?
您可以简单地借助自定义 class 实现 ApplicationListener 并将其定义为 spring-factories 条目中的 startupup class 之一来查看应用程序属性,因此它们将在应用程序加载之前执行。步骤如下:-
a) 在资源 class 路径中创建一个名为 spring.factories 的文件,即 src\main\resources\META-INF\spring.factories 内容为 -
# Application Listeners
org.springframework.context.ApplicationListener=demo.CustomConfigListener
b) 在您的项目中创建一个自定义侦听器 class,就像这里的 CustomConfigListener
package demo;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
public class CustomConfigListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
for(PropertySource<?> source : ((ApplicationEnvironmentPreparedEvent) event).getEnvironment().getPropertySources()){
if(source.getName().equals("applicationConfigurationProperties")){
if (source instanceof EnumerablePropertySource) {
for(String name : ((EnumerablePropertySource) source).getPropertyNames()){
System.out.println(name+" :: "+ ((EnumerablePropertySource) source).getProperty(name));
}
}
}
}
}
}
}
c) 您的自定义 ConfigurationProperties class
package demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
private String host;
private int port;
private Smtp smtp;
//Getters & Setters
public static class Smtp {
private boolean auth;
private boolean starttlsEnable;
//Getters & Setters
}
}
d) 最后你的 application.properties
mail.host=localhost
mail.port=25
mail.smtp.auth=false
mail.smtp.starttls-enable=false
作为@Avis 回答的后续,我意识到该片段不包含任何命令行参数等,因此我稍微更新了他的概念。我附上了我的记录器 class 以防它对将来解决这个问题的任何人有价值。
public class ConfigurationLogger implements ApplicationListener<ApplicationEvent> {
// slf4j logger
private static final Logger logger = LoggerFactory.getLogger(ConfigurationLogger.class);
// used to sanitize any password sensitive keys (copied from Spring Boot's Sanitizer() class
private Sanitizer sanitizer = new Sanitizer();
// store the config keys in a sorted map
private Map<String, Object> configurationProperties = new TreeMap<>();
/**
* Trigger upon all events during startup. Both ApplicatoinEnvironmentPrepareEvent and
* ApplicationPreparedEvent need access to the same configurationProperties object. Could
* have done this through separate events, both extending an abstract base class with a static
* hash map, but not worth the effort. Instead have the same class listen for all events, and
* delegate to the appropriate method.
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
// store the values
onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
}else if( event instanceof ApplicationPreparedEvent){
// display the values
logConfigurationProperties( (ApplicationPreparedEvent)event);
}
}
/**
* Store the properties in the hash map for logging once all property sources have been read
*
* @param event
*/
private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
for (PropertySource<?> source : event.getEnvironment().getPropertySources()) {
if (source instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) source).getPropertyNames()) {
Object value = ((EnumerablePropertySource) source).getProperty(key);
if (!configurationProperties.containsKey(key)) {
configurationProperties.put(key, sanitizer.sanitize(key, value));
}
}
}
}
}
/**
* Print all the config properties to the logger
*/
private void logConfigurationProperties( ApplicationPreparedEvent event) {
logger.debug("Application started with following parameters: ");
for( Map.Entry<String, Object> entry : configurationProperties.entrySet()){
logger.debug("{} :: {}", entry.getKey(), entry.getValue());
}
}
}
并且在SpringApplication main中初始化监听class:
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
// add configuration properties logger
app.addListeners(new ConfigurationLogger());
app.run(args);
}
}
我正在尝试找到一种方法来在上下文启动之前记录我的应用程序属性(通过@ConfigurationProperties 注入到我的 bean 中),以便我可以在所有 bean 初始化之前看到确切的属性。
我已尝试在 ApplicationEnvironmentPreparedEvent 上创建一个侦听器,但除了一次检索一个单独的属性外,无法检索所有定义的属性。
有没有简单的方法来做到这一点?某种方法可以先初始化 @ConfigurationProperties
并记录它们的内容,或者在上下文创建之前检索所有应用程序启动属性?
您可以简单地借助自定义 class 实现 ApplicationListener 并将其定义为 spring-factories 条目中的 startupup class 之一来查看应用程序属性,因此它们将在应用程序加载之前执行。步骤如下:-
a) 在资源 class 路径中创建一个名为 spring.factories 的文件,即 src\main\resources\META-INF\spring.factories 内容为 -
# Application Listeners
org.springframework.context.ApplicationListener=demo.CustomConfigListener
b) 在您的项目中创建一个自定义侦听器 class,就像这里的 CustomConfigListener
package demo;
import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.core.env.PropertySource;
public class CustomConfigListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
for(PropertySource<?> source : ((ApplicationEnvironmentPreparedEvent) event).getEnvironment().getPropertySources()){
if(source.getName().equals("applicationConfigurationProperties")){
if (source instanceof EnumerablePropertySource) {
for(String name : ((EnumerablePropertySource) source).getPropertyNames()){
System.out.println(name+" :: "+ ((EnumerablePropertySource) source).getProperty(name));
}
}
}
}
}
}
}
c) 您的自定义 ConfigurationProperties class
package demo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(ignoreUnknownFields = false, prefix = "mail")
public class MailProperties {
private String host;
private int port;
private Smtp smtp;
//Getters & Setters
public static class Smtp {
private boolean auth;
private boolean starttlsEnable;
//Getters & Setters
}
}
d) 最后你的 application.properties
mail.host=localhost
mail.port=25
mail.smtp.auth=false
mail.smtp.starttls-enable=false
作为@Avis 回答的后续,我意识到该片段不包含任何命令行参数等,因此我稍微更新了他的概念。我附上了我的记录器 class 以防它对将来解决这个问题的任何人有价值。
public class ConfigurationLogger implements ApplicationListener<ApplicationEvent> {
// slf4j logger
private static final Logger logger = LoggerFactory.getLogger(ConfigurationLogger.class);
// used to sanitize any password sensitive keys (copied from Spring Boot's Sanitizer() class
private Sanitizer sanitizer = new Sanitizer();
// store the config keys in a sorted map
private Map<String, Object> configurationProperties = new TreeMap<>();
/**
* Trigger upon all events during startup. Both ApplicatoinEnvironmentPrepareEvent and
* ApplicationPreparedEvent need access to the same configurationProperties object. Could
* have done this through separate events, both extending an abstract base class with a static
* hash map, but not worth the effort. Instead have the same class listen for all events, and
* delegate to the appropriate method.
*/
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
// store the values
onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
}else if( event instanceof ApplicationPreparedEvent){
// display the values
logConfigurationProperties( (ApplicationPreparedEvent)event);
}
}
/**
* Store the properties in the hash map for logging once all property sources have been read
*
* @param event
*/
private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
for (PropertySource<?> source : event.getEnvironment().getPropertySources()) {
if (source instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) source).getPropertyNames()) {
Object value = ((EnumerablePropertySource) source).getProperty(key);
if (!configurationProperties.containsKey(key)) {
configurationProperties.put(key, sanitizer.sanitize(key, value));
}
}
}
}
}
/**
* Print all the config properties to the logger
*/
private void logConfigurationProperties( ApplicationPreparedEvent event) {
logger.debug("Application started with following parameters: ");
for( Map.Entry<String, Object> entry : configurationProperties.entrySet()){
logger.debug("{} :: {}", entry.getKey(), entry.getValue());
}
}
}
并且在SpringApplication main中初始化监听class:
@SpringBootApplication
public class Application{
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setShowBanner(false);
// add configuration properties logger
app.addListeners(new ConfigurationLogger());
app.run(args);
}
}