BeanFactoryPostProcessor

BeanFactoryPostProcessor

本文介绍了访问BeanFactoryPostProcessor中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一些东西,这些东西将基于可配置的属性(来自 application.yml 等)自动创建bean.

I am trying to create something which will auto-create beans based on configurable properties (from application.yml and the like).

由于我不能像通常在 BeanFactoryPostProcessor 中那样访问属性组件,所以我很困惑如何访问它们.

Since I can't just access the properties component like I normally would in the BeanFactoryPostProcessor, I'm kind of stumped how I can access them.

如何在 BeanFactoryPostProcessor 中访问应用程序属性?

How can I access application properties in BeanFactoryPostProcessor?

推荐答案

如果要在 BeanFactoryPostProcessor 中以类型安全的方式访问属性,则需要从中绑定它们使用 Binder API自己>环境.从本质上讲,这就是Boot本身为支持 @ConfigurationProperties Bean所做的工作.

If you want to access properties in a type-safe manner in a BeanFactoryPostProcessor you'll need to bind them from the Environment yourself using the Binder API. This is essentially what Boot itself does to support @ConfigurationProperties beans.

您的 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
        }

    };
}

这篇关于访问BeanFactoryPostProcessor中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 14:31