【发布时间】:2019-04-26 07:33:03
【问题描述】:
我维护了一个 spring-boot-starter 来定制返回的错误属性,例如,一个未知的端点被调用。 这是通过覆盖 org.springframework.boot.web.servlet.error.ErrorAttributes bean 来完成的。
在 2.0.6 中一切正常,但 2.1.0 disables bean overriding by default,导致启动器现在失败并显示以下消息。
类中定义的名称为“errorAttributes”的无效 bean 定义 路径资源 [com/mycompany/springboot/starter/config/ErrorsConfig.class]:不能 注册bean定义[根bean:类[null];范围=; 摘要=假;懒惰初始化=假;自动线模式=3;依赖检查=0; 自动接线候选=真;主要=假; factoryBeanName=com.mycompany.springboot.starter.config.ErrorsConfig; factoryMethodName=errorAttributes;初始化方法名=空; destroyMethodName=(推断);在类路径资源中定义 [com/mycompany/springboot/starter/config/ErrorsConfig.class]] 用于 bean 'errorAttributes': 已经有 [Root bean: class [null];范围=; 摘要=假;懒惰初始化=假;自动线模式=3;依赖检查=0; 自动接线候选=真;主要=假; factoryBeanName=org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; factoryMethodName=errorAttributes;初始化方法名=空; destroyMethodName=(推断);在类路径资源中定义 [org/springframework/boot/autoconfigure/web/servlet/error/ErrorMvcAutoConfiguration.class]] 绑定
如文档中所述,将 spring.main.allow-bean-definition-overriding 属性设置为 true 可以解决问题。 我的问题是如何在启动器中(我不希望启动器的用户必须更改他们的 application.properties 文件,以获取特定于我的启动器的内容)?
我尝试使用在该文件中定义的属性对我的@Configuration 进行@PropertySource("classpath:/com/mycompany/starter/application.properties") 注释,但它不起作用。
我错过了什么?有什么方法可以让我的配置覆盖该 bean?
这是配置的(简化的)源代码:
@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);
}
};
}
}
我的资源文件 com/mycompany/starter/application.properties 包含
spring.main.allow-bean-definition-overriding=true
【问题讨论】:
标签: spring-boot spring-boot-configuration