Search code examples
javaspringspring-bootannotations

@ConditionalOnProperty: does it have an impact only on annotation specified below?


Assume, that we have the following peace of the code:

@SpringBootApplication
@ConditionalOnProperty(value = "scheduling.enable")
@EnableScheduling
@EnableCaching
public class AcmeServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(AcmeServiceApplication.class, args);
    }
}

Does @ConditionalOnProperty annotation will enable\disable only @EnableScheduling or it will have an impact on @EnableCaching as well?

Did not find an answer in the documentation.


Solution

  • When a condition, such as @ConditionalOnProperty, is used on a class, it controls whether or not the whole class is processed. When it is used on a @Bean method, it controls whether or not the individual method is processed.

    In the case of your specific example, if the condition matches, AcmeServiceApplication will be processed and therefore both scheduled and caching will be enabled and @SpringBootApplication will take effect by enabling auto-configuration and component scanning. If the condition does not match, AcmeServiceApplication will not be processed and therefore neither scheduling nor caching will be enabled and @SpringBootApplication will have no effect.