我正在尝试找到一种方法来在上下文启动之前记录我的应用程序属性(通过 @ConfigurationProperties 注入(inject)到我的 bean 中),以便我可以在初始化所有 bean 之前查看确切的属性。
我尝试在 ApplicationEnvironmentPreparedEvent 上创建监听器,但除了一次检索单个属性之外,无法检索所有定义的属性。
有没有简单的方法可以做到这一点?有什么方法可以首先初始化@ConfigurationProperties并记录其内容,或者在创建上下文之前检索所有应用程序启动属性?
最佳答案
您可以简单地借助实现 ApplicationListener 的自定义类并将其定义为 spring-factories 条目中的启动类之一来查看应用程序属性,以便它们将在应用程序加载之前执行。步骤如下:-
a)在资源类路径中创建一个名为 spring.factories 的文件,即 src\main\resources\META-INF\spring.factories ,其内容为 -
# Application Listeners
org.springframework.context.ApplicationListener=demo.CustomConfigListener
b) 在您的项目中创建一个自定义监听器类,如下所示 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 类
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
关于java - 在启动之前在SpringBoot中记录@ConfigurationProperties?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33072452/