Springboot 整合 Mybatis,不同package下同名mapper啟動報錯
Mybatis不同包裡出現了同名類,啟動時報錯如下:
org.springframework.context.annotation.ConflictingBeanDefinitionException: Annotation-specified bean name 'sysSetMapper' for bean class [com.onlyas.appserver.dao.SysSetMapper] conflicts with existing, non-compatible bean definition of same name and class [com.onlyas.appserver.dao.dbo.SysSetMapper]
通過檢視Spring原始碼得知,當我們使用註解建立bean時,spring使用了AnnotationBeanNameGenerator來建立bean的名稱。
解決方案:自己寫一個Generator吧。如下:
@SpringBootApplication @ComponentScan(nameGenerator = MultidataApplication.SpringBeanNameGenerator.class) public class MultidataApplication { public static class SpringBeanNameGenerator extends AnnotationBeanNameGenerator { @Override protected String buildDefaultBeanName(BeanDefinition definition) { return definition.getBeanClassName(); } } public static void main(String[] args) { SpringApplication.run(MultidataApplication.class, args); } }
Mybatis的MapperScan裡新增:
nameGenerator = MultidataApplication.SpringBeanNameGenerator.class
示例:
@MapperScan(basePackages="com.onlyas.appserver.dao", nameGenerator = MultidataApplication.SpringBeanNameGenerator.class)
好了,這樣再執行起來就不會報錯了。