23

I maintain a spring-boot-starter that customizes the error attributes returned when, for instance, an unknown endpoint is called. This is done by overriding the org.springframework.boot.web.servlet.error.ErrorAttributes bean.

Everything worked fine with 2.0.6, but 2.1.0 disables bean overriding by default, making the starter now fail with the following message.

Invalid bean definition with name 'errorAttributes' defined in class path resource [com/mycompany/springboot/starter/config/ErrorsConfig.class]: Cannot register bean definition [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=com.mycompany.springboot.starter.config.ErrorsConfig; factoryMethodName=errorAttributes; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [com/mycompany/springboot/starter/config/ErrorsConfig.class]] for bean 'errorAttributes': There is already [Root bean: class [null]; scope=; abstract=false; lazyInit=false; autowireMode=3; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; factoryMethodName=errorAttributes; initMethodName=null; destroyMethodName=(inferred); defined in class path resource [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class]] bound

As explained in the documentation setting the spring.main.allow-bean-definition-overriding property to true fixes the problem. My question is how to do that in the starter (I do not want the users of my starter to have to change their application.properties file, for something that is specific to my starter)?

I tried to a @PropertySource("classpath:/com/mycompany/starter/application.properties") annotation to my @Configuration with that property defined in that file, but it doesn't work.

What am I missing? Is there any way to allow my configuration to override that bean?

Here is the (simplified) source code of the configuration:

@Configuration
@PropertySource("classpath:/com/mycompany/starter/application.properties")
public class ErrorsConfig {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    @Bean
    public ErrorAttributes errorAttributes() {
        return new DefaultErrorAttributes() {
            @SuppressWarnings("unchecked")
            @Override
            public Map<String, Object> getErrorAttributes(WebRequest request, boolean includeStackTrace) {
                Map<String, Object> errorAttributes = super.getErrorAttributes(request, includeStackTrace);
                // CustomeError is a (simplified) bean of the error attributes we should return.
                CustomError err = new CustomError("myErrorCode", (String) errorAttributes.get("error"));
                return OBJECT_MAPPER.convertValue(err, Map.class);
            }
        };
    }
}

and my resource file com/mycompany/starter/application.properties contains

spring.main.allow-bean-definition-overriding=true

Archmede
  • 1,592
  • 2
  • 20
  • 37
Jean-Marc Astesana
  • 1,242
  • 3
  • 16
  • 24

3 Answers3

18

Spring Boot's ErrorAttributes bean is defined by ErrorMvcAutoConfiguration. It is annotated with @ConditionalOnMissingBean so it will back off if an ErrorAttributes bean has already been defined. As the bean defined by your ErrorsConfig class is attempting to override Boot's ErrorAttributes bean rather than causing it to back off, your ErrorsConfig class must be getting processed after Boot's ErrorMvcAutoConfiguration class. This means that you have an ordering problem in your starter.

The order in which auto-configuration classes are processed can be controlled using @AutoConfigureBefore and @AutoConfigureAfter. Assuming that ErrorsConfig is itself an auto-configuration class registered in spring.factories, you can fix your problem by annotating it with @AutoConfigureBefore(ErrorMvcAutoConfiguration.class). With this change in place ErrorsConfig will define its ErrorAttributes bean before ErrorMvcAutoConfiguration attempts to do so which will cause the auto-configuration of Boot's ErrorsAttribute bean to back off.

Andy Wilkinson
  • 108,729
  • 24
  • 257
  • 242
  • Andy: What if ErrorsConfig is not auto-configuration? Is there a similar mechanism or do I have to use unique name or exclude the ErrorMvcAutoConfiguration? – jorgen.ringen Apr 23 '19 at 14:30
  • Normal configuration should run before any auto-configuration. If you're not writing your own auto-configuration you should not have the problem addressed here. – Andy Wilkinson Apr 23 '19 at 15:59
  • I've created a small sample that shows the behaviour with spring-batch: https://github.com/JorgenRingen/spring-boot-spring-batch-bean-overriding I'm adding @EnableBatchProcessing and configuring my own JobLauncher bean with the same name as the spring-batch autoconfiguration uses and get error-message telling that a bean with that name already exists on classpath (let me know if I should raise an issue on github) – jorgen.ringen Apr 24 '19 at 07:08
  • 1
    @jorgen.ringen That problem really isn't related to this question and answer. Batch expects the `JobLauncher` to be provided via a `BatchConfigurer` bean rather than being directly configured as a bean. – Andy Wilkinson Apr 24 '19 at 09:07
13

Easier solution would be to add this property spring.main.allow-bean-definition-overriding=true in the application.properties.

Reference

Muhammad Waqas Dilawar
  • 1,844
  • 1
  • 23
  • 34
Sai Kumar Reddy
  • 155
  • 1
  • 3
0

I have also faced similar issue. But the problem in my case is that, I was using @Entity annotaion in my model class. I was using mongodb for the backend so entity was from Jpa and hence resulted in this issue. Once I removed that it started working

Jeeva D
  • 304
  • 1
  • 4
  • 15