问题描述
我有 bean (transformerColumnKeyLoader),它应该在 DataSourceAutoConfiguration 之前初始化.该 bean 的目的是用密钥替换实体属性注释中的占位符.我以前有过运行良好的配置代码(顺序很好):
I have bean (transformerColumnKeyLoader) which sould be inited before DataSourceAutoConfiguration. Purpose of that bean is replace placeholers in anotation on entity properties with key for cyphering. I had that code of configuration which worked well before (order was good):
@Configuration(proxyBeanMethods = false)
@Import(DataSourceAutoConfiguration.class) // dependent configuration
@DependsOn("transformerColumnKeyLoader") // bean which has priority
public class DatasourceAutoConfig {
}
但是在添加了一些新 bean 之后,现在不起作用了.首先初始化的是DataSourceAutoConfiguration,然后是初始化transformerColumnKeyLoader bean.
But after adding some new beans, now isn't working. And first initialized is DataSourceAutoConfiguration and after that init transformerColumnKeyLoader bean.
推荐答案
我找到了简单的解决方案.我打破了解决依赖关系的 bean,我正在通过 Spring 应用程序事件触发.我的灵感来自评论.我的解决方案是:
I found simple solution. I break bean out of resolving dependencies and I'm trigering by Spring application event. I had inspiration by comment. My solution is:
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 之前触发.
The great is I'm able to access to properties and this is trigered before all beans.
这篇关于DataSourceAutoConfiguration 之前的 Bean init的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!