我正在尝试创建一些东西,它会根据可配置的属性(来自 application.yml
等)自动创建 bean。
由于我不能像通常在 BeanFactoryPostProcessor
中那样访问属性组件,所以我对如何访问它们感到困惑。
如何访问 BeanFactoryPostProcessor
中的应用程序属性?
最佳答案
如果您想在 BeanFactoryPostProcessor
中以类型安全的方式访问属性,您需要使用 Binder< 从
API。这本质上是 Boot 本身为支持 Environment
中自行绑定(bind)它们@ConfigurationProperties
bean 所做的。
您的 BeanFactoryPostProcessor
看起来像这样:
@Bean
public static BeanFactoryPostProcessor beanFactoryPostProcessor(
Environment environment) {
return new BeanFactoryPostProcessor() {
@Override
public void postProcessBeanFactory(
ConfigurableListableBeanFactory beanFactory) throws BeansException {
BindResult<ExampleProperties> result = Binder.get(environment)
.bind("com.example.prefix", ExampleProperties.class);
ExampleProperties properties = result.get();
// Use the properties to post-process the bean factory as needed
}
};
}
关于java - 访问 BeanFactoryPostProcessor 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53851533/