Spring - 与同名和类的现有非兼容bean定义冲突

时间:2018-05-26 17:20:58

标签: java spring autowired spring-mybatis

具体例外是:

Failed to instantiate [org.springframework.context.annotation.AnnotationConfigApplicationContext]: Constructor threw exception;
nested exception is org.springframework.context.annotation.ConflictingBeanDefinitionException:
Annotation-specified bean name 'myService' for bean class [my.package.ejb.MyService] conflicts with existing, non-compatible bean definition of same name and class [my.package.other.ejb.MyService]

这些MyService接口甚至没有注释,它们代表EJB 2.0无状态bean。

我的注释配置如下。

@Configuration
@ComponentScan("my.package")
@MapperScan("my.package")
public class ApplicationConfiguration {
    @Bean
    public DataSource dataSource() {
        return new JndiDataSourceLookup().getDataSource("...");
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(final DataSource dataSource) {
        final SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(dataSource);
        sqlSessionFactory.setConfigLocation(new ClassPathResource("..."));
        return sqlSessionFactory;
    }

    @Bean
    public DataSourceTransactionManager dataSourceTransactionManager(final DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}

可能与@MapperScan(来自MyBatis)和@ComponentScan不兼容?

异常来自SpringBeanAutowiringInterceptor我用于Autowire EJB 3.0字段。

2 个答案:

答案 0 :(得分:1)

该错误表明您有两个同名的bean(myService)但不兼容:

my.package.ejb.MyService
my.package.other.ejb.MyService

在这种情况下,您应该为bean定义唯一的名称:

@Bean(name = "myService1")
@Component
public MyService {
... Define another name for other service

答案 1 :(得分:0)

MapperScannerConfigurer的文档说:

  

此类支持过滤通过指定创建的映射器   标记界面或注释。 annotationClass属性   指定要搜索的注释。 markerInterface属性   指定要搜索的父接口。如果两个属性都是   指定的,为与之匹配的接口添加映射器   标准。 默认情况下,这两个属性为null,因此所有接口都是如此   在给定的basePackage中添加为mappers

基本上我将数千个接口映射为bean。不酷!
伙计们,我的错。