I'd like to enable custom configuration and sensible defaults using @ConditionalOnMissingBean
?
I have a spring boot application:
@Configuration
@Import({CustomConfiguration.class, DefaultConfiguration.class})
@EnableAutoConfiguration(exclude={MetricFilterAutoConfiguration.class})
public class Application {
@Autowired
ErrorListener errorListener;
}
and a CustomConfiguration
that allows for either Spring xml or component scanning:
@Configuration("customConfiguration")
@ImportResource("classpath:customContext.xml")
@ComponentScan({"org.custom.impl"})
public class CustomConfiguration
The DefaultConfiguration
uses ConditionalOnMissingBean
:
@Bean
@ConditionalOnMissingBean
ErrorListener errorListener() {
return new LoggingErrorListener();
}
What I'm trying to achieve is allow for a custom ErrorListener
to be defined in the classpath, if not defined then use the default LoggingErrorListener
(via the ConditionalOnMissingBean
). I'm finding that the DefaultConfiguration
is always being used before the CustomConfiguration
.
I've been experimenting with @DependsOn
and @Order
but no joy.
@EnableAutoConfiguration : enable Spring Boot's auto-configuration mechanism. @ComponentScan : enable @Component scan on the package where the application is located (see the best practices) @Configuration : allow to register extra beans in the context or import additional configuration classes.
Spring @Configuration annotation is part of the spring core framework. Spring Configuration annotation indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application.
In order to create a custom auto-configuration, we need to create a class annotated as @Configuration and register it. Next, we need to register the class as an auto-configuration candidate. If we want our auto-configuration class to have priority over other candidates, we can add the @AutoConfigureOrder(Ordered.
I wouldn't use @ConditionalOnMissingBean
outside of an auto-configuration class if I were you, unless you can control the order of import of @Configuration
classes. Auto-configuration does it explicitly, but normal user config classes (especially if they are @ComponentSCanned
) do not have a defined order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With