在 Spring Boot 3 中覆盖 localeResolver bean

问题描述 投票:0回答:3

在迁移到 Spring Boot 3 之前,我创建了

localeResolver
bean,如下所示:

@Bean
public LocaleResolver localeResolver(MessageSourceProperties properties) {
    CookieLocaleResolver clr = new CookieLocaleResolver(properties.getCookieName());
    clr.setDefaultLocale(Locale.ENGLISH);
    return clr;
}

但是现在这个 bean 已经定义了,我收到错误:

The bean 'localeResolver', defined in class path resource [com/app/autoconfigure/internationalization/I18nAutoConfiguration.class], could not be registered. A bean with that name has already been defined in class path resource [org/springframework/web/servlet/config/annotation/DelegatingWebMvcConfiguration.class] and overriding is disabled.

这个bean是在类

WebMvcConfigurationSupport
中创建的。

如何覆盖它?

java spring spring-boot
3个回答
0
投票

在尝试使用

@AutoConfiguration
从库导入的配置中创建 bean 时也遇到了这个问题。
LocaleResolver
bean 是在
WebMvcAutoConfiguration
中创建的,它具有
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 10)
,我提供的配置应该具有更高的优先级,因此将
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE + 9)
添加到我的配置类中解决了该问题。

请记住,这仅在您的应用程序没有

@EnableWebMvc
注释时才有效


0
投票

经过多次搜索,我找到了最好的解决方案:

删除您在 Spring Boot 项目中配置的 @EnableWebMvc 注解。

https://github.com/spring-projects/spring-framework/issues/25290


-2
投票

有两种方法可以解决这个问题:

  1. 将方法名称“localeResolver”更改为其他名称;因为“Spring 将带注释的方法的名称作为 bean 名称。”

  2. 设置@Bean注解的name属性。

作为参考,您可以遵循: https://www.baeldung.com/spring-boot-bean-definition-override-exception

© www.soinside.com 2019 - 2024. All rights reserved.