抑制@ComponentScan的ConflictingBeanDefinitionException

时间:2017-02-17 16:05:10

标签: java spring swagger springfox

我有一个 Spring 项目,其中多个bean可能具有相同的bean名称。

为了避免ConflictingBeanDefinitionException项目被覆盖ContextNamespaceHandler

public class ContextNamespaceHandler extends NamespaceHandlerSupport {

    @Override
    public void init() {
        registerBeanDefinitionParser("component-scan", new ComponentScanBeanDefinitionParser() {
            @Override
            protected ClassPathBeanDefinitionScanner createScanner(XmlReaderContext readerContext, boolean useDefaultFilters) {
                return new ClassPathBeanDefinitionScanner(readerContext.getRegistry(), useDefaultFilters) {
                    @Override
                    protected boolean checkCandidate(String beanName, BeanDefinition beanDefinition) throws IllegalStateException {
                        return true;
                    }
                };
            }
        });
    }

}

我使用 Swagger / Springfox 为项目生成API文档。

@Configuration
@EnableWebMvc
@EnableSwagger2
@ComponentScan(basePackages = { "some.package", "some.other.package" })
public class SwaggerConfig {
   // ...
}

@ComponentScan导致ConflictingBeanDefinitionException,因为它使用的是默认ClassPathBeanDefinitionScanner而不是被覆盖的。{/ p>

Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'xxx' for bean class [xxx] conflicts with existing, non-compatible bean definition of same name and class [xxx]
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:320)
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:259)
    at org.springframework.context.annotation.ComponentScanAnnotationParser.parse(ComponentScanAnnotationParser.java:140)
    at org.springframework.context.annotation.ConfigurationClassParser.doProcessConfigurationClass(ConfigurationClassParser.java:262)
    at org.springframework.context.annotation.ConfigurationClassParser.processConfigurationClass(ConfigurationClassParser.java:226)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:193)
    at org.springframework.context.annotation.ConfigurationClassParser.parse(ConfigurationClassParser.java:163)
    ... 22 more

有没有办法覆盖ClassPathBeanDefinitionScanner使用的@ComponentScan或其他方式来压制ConflictingBeanDefinitionException

1 个答案:

答案 0 :(得分:0)

这里最好的方法通常是通过在注释中指定bean名称来使每个bean名称唯一,即:

@Service("someService")

现在,您可以指定自动装配时要使用的bean的名称:

@Autowired
@Qualifier("someService")

即使通用对象存在被覆盖的组件,指定名称通常也是一个好主意,以便明确区分。抑制异常通常被认为不是好习惯。希望这有帮助!