Skip to content

Bean init before DataSourceAutoConfiguration

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 {

But after adding some new beans, now isn’t working. And first initialized is DataSourceAutoConfiguration and after that init transformerColumnKeyLoader bean.


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;

Event Listener

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
    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);


The great is I’m able to access to properties and this is trigered before all beans.