Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@ConditionalOnBean not working with JdbcTemplate.class

I have some spring component:

@Component
@ConditionalOnBean(value={JdbcTemplate.class})
public class DictionaryHandler implements Handler {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DictionaryHandler(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //some methods
}

In debug, I see, that JdbcTemplate bean was created: enter image description here

But, my bean not created.It doesn't go into the constructor. But why? Bean JdbcTemplate is exist, but my bean not created.

Does the condition work wrong? I don't want create DictionaryHandler if JdbcTemplate is missing. Without this I get an error.

like image 613
All_Safe Avatar asked Nov 02 '25 04:11

All_Safe


2 Answers

You should use @ConditionalOnBean on auto configuration classes only (otherwise the order is unspecified)

The condition can only match the bean definitions that have been processed by the application context so far and, as such, it is strongly recommended to use this condition on auto-configuration classes only. If a candidate bean may be created by another auto-configuration, make sure that the one using this condition runs after.

Since your JdbcTemplate bean is defined inside JdbcTemplateAutoConfiguration class so I assume that JdbcTemplateAutoConfiguration is marked with @Configuration.

In that case, you can ensure the instantiate of your bean by config:

@Configuration
@AutoConfigureAfter(JdbcTemplateAutoConfiguration.class)
public class DicationaryHandlerConfiguration {

    @Bean
    @ConditionalOnBean(JdbcTemplate.class)
    public DictionaryHandler handler(JdbcTemplate jdbcTemplate) {
         return new DictionaryHandler(jdbcTemplate)
    }

}

public class DictionaryHandler implements Handler {

    private final JdbcTemplate jdbcTemplate;

    public DictionaryHandler(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    //some methods
}
like image 162
Mạnh Quyết Nguyễn Avatar answered Nov 03 '25 19:11

Mạnh Quyết Nguyễn


Check the documentation for ConditionalOnBean. It runs once and if the bean it requires not yet created - it will not trigger. The order of bean creation matters. You can try to lower priority of your component with @Order annotation or increase priority of you configuration/component class which holds JdbcTemplate bean.

like image 22
vlaku Avatar answered Nov 03 '25 20:11

vlaku



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!