Я пытаюсь выполнить миграцию с Springboot 1.x.y (Brussels-SR12) на 2.x.y. Пользуюсь FeignClients
Я меняю конфигурацию Maven:
<spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
так
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-openfeign</artifactId>
<version>2.0.0.RELEASE</version>
Меняю весь импорт:
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.cloud.netflix.feign.FeignClient;
к
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
Я использую этот интерфейс:
@FeignClient(value = "COMPANY", fallbackFactory = CompanyClientFallbackFactory.class, configuration = FeignConfiguration.class)
public interface CompanyClient extends CompanyApi {
}
Когда я запускаю свои тесты JUnit (с контекстом Spring), у меня появляется эта ошибка (не в Springboot 1.x.y и старом пакете netflix):
The bean 'COMPANY.FeignClientSpecification', defined in null, could not be registered. A bean with that name has already been defined in null and overriding is disabled.
Полная трассировка:
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:125)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:108)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.postProcessFields(MockitoTestExecutionListener.java:99)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.injectFields(MockitoTestExecutionListener.java:79)
at org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener.prepareTestInstance(MockitoTestExecutionListener.java:54)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:246)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:227)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:289)
...
Caused by: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'COMPANY.FeignClientSpecification' defined in null: Cannot register bean definition [Generic bean: class [org.springframework.cloud.openfeign.FeignClientSpecification]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] for bean 'COMPANY.FeignClientSpecification': There is already [Generic bean: class [org.springframework.cloud.openfeign.FeignClientSpecification]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.
at org.springframework.beans.factory.support.DefaultListableBeanFactory.registerBeanDefinition(DefaultListableBeanFactory.java:896)
at org.springframework.cloud.openfeign.FeignClientsRegistrar.registerClientConfiguration(FeignClientsRegistrar.java:355)
at org.springframework.cloud.openfeign.FeignClientsRegistrar.registerFeignClients(FeignClientsRegistrar.java:155)
at org.springframework.cloud.openfeign.FeignClientsRegistrar.registerBeanDefinitions(FeignClientsRegistrar.java:83)




Я нашел решение, но это обходной путь. См. Ответ @Alessandro Dionisi
application.yml:
spring:
main:
allow-bean-definition-overriding: true
это абсолютно обходной путь, вы должны подумать о том, чтобы переименовать своих фальшивых клиентов или разделить друг друга разными URL-адресами.
этот обходной путь приведет вас к более сложным проблемам, потому что он маскирует проблемы с вашими bean-компонентами.
@ Lu55, см. Ответ Алессандро Диониси
Возможно, у вас есть несколько определений @FeignClient с одинаковым атрибутом имени.
это решение от Имитация документации:
If we want to create multiple feign clients with the same name or url so that they would point to the same server but each with a different custom configuration then we have to use
contextIdattribute of the@FeignClientin order to avoid name collision of these configuration beans.@FeignClient(contextId = "fooClient", name = "stores", configuration = FooConfiguration.class) public interface FooClient { //.. } @FeignClient(contextId = "barClient", name = "stores", configuration = BarConfiguration.class) public interface BarClient { //.. }
Рассмотрите возможность переименования одного из bean-компонентов или включения переопределения, установив spring.main.allow-bean-definition-overriding = true
Вы копируете / вставляете мой ответ, но это не решение, а обходной путь
Это также может произойти, если у вас случайно есть более одного класса @Configuration, аннотированного с помощью @EnableFeignClients.
Это исправило это для меня. Но я все же хотел бы иметь две отдельные конфигурации в разных модулях.
Пакет mvn clean исправил эту ошибку для меня
Да, это обходной путь, но не решение, спасибо @AlessandroDionisi