What does the spring annotation @ConditionalOnMissingBean do?

前端 未结 4 1576
囚心锁ツ
囚心锁ツ 2020-12-31 00:25

I am trying to start a springboot application where this annotation has been used. When I try to start the application it gives me the following error:

<
4条回答
  •  囚心锁ツ
    2020-12-31 00:49

    We use @ConditionalOnMissingBean if we want to include a bean only if a specified bean is not present. For ex.

    Let's configure a transactionManager bean that will only be loaded if a bean of type JpaTransactionManager is not already defined:

    @Bean
    @ConditionalOnMissingBean(type = "JpaTransactionManager")
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    }
    

    To understand more consider this scenario as well.

    Let's say in my project I configured a bean videoDecoderService

    @Bean
    @ConditionalOnMissingBean(VideoDecoderService.class)
    public videoDecoderService videoDecoderService(){
    return new VideoDecoderService;
    }
    

    What it will do is whoever is using my project would be able to override the videoDecoderService with the videoDecoderService of their own. If they are not writing their own videoDecoderService then this default one will be provided.

提交回复
热议问题