Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring configuration class loading order with spring-boot @ConditionalOnMissingBean?

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.

like image 878
Gethin James Avatar asked Dec 19 '14 15:12

Gethin James


People also ask

What is the difference between @configuration and @EnableAutoConfiguration?

@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.

What @configuration does in spring boot?

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.

How do you customize spring boot auto-configuration?

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.


1 Answers

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.

like image 153
Dave Syer Avatar answered Oct 23 '22 12:10

Dave Syer