【问题标题】:Bean init before DataSourceAutoConfigurationDataSourceAutoConfiguration 之前的 Bean 初始化
【发布时间】:2020-12-16 10:47:50
【问题描述】:

我有 bean (transformerColumnKeyLoader),它应该在 DataSourceAutoConfiguration 之前被初始化。该 bean 的目的是将实体属性注释中的占位符替换为加密密钥。我有之前运行良好的配置代码(订单很好):

@Configuration(proxyBeanMethods = false)
@Import(DataSourceAutoConfiguration.class) // dependent configuration
@DependsOn("transformerColumnKeyLoader") // bean which has priority
public class DatasourceAutoConfig {
}

但是在添加了一些新的 bean 之后,现在无法正常工作。首先初始化的是 DataSourceAutoConfiguration ,然后是初始化 transformerColumnKeyLoader bean。

【问题讨论】:

    标签: java spring spring-boot


    【解决方案1】:

    我找到了简单的解决方案。我打破了 bean 解决依赖关系的问题,我正在通过 Spring 应用程序事件触发。我的灵感来自comment。我的解决方案是:

     public static void main(final String[] args) {
            SpringApplication springApplication = new SpringApplication(KBPaymentApp.class);
            springApplication.addListeners(new EnvironmentPreparedEventListener()); // adding application event listener
            springApplication.run(args);
        }
    

    事件监听器

    public class EnvironmentPreparedEventListener implements ApplicationListener<ApplicationEnvironmentPreparedEvent> {
    
        private static final String CRYPTO_SECRET_ENV_PROPERTY_KEY = "psd2.token.encrypt.key"; // path to variable from appliaction.yaml
    
        /**
         * execute after env variables are ready
         *
         * @param event ApplicationEnvironmentPreparedEvent
         */
        @Override
        public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) {
            // get properties
            ConfigurableEnvironment environment = event.getEnvironment();
            String cryptoSecret = environment.getProperty(CRYPTO_SECRET_ENV_PROPERTY_KEY);
            
            // init and perform action before DataSourceAutoConfiguration created
            TransformerColumnKeyLoader transformerColumnKeyLoader = new TransformerColumnKeyLoader(cryptoSecret);
            transformerColumnKeyLoader.executeTransformer();
    
        }
    }
    

    很棒的是我能够访问属性,并且在所有 bean 之前触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-02
      • 1970-01-01
      • 2020-08-30
      相关资源
      最近更新 更多