今天在测试maven插件mybatic-generator自动生产pojo以及Mapper映射文件时发现一个问题。
我生成的Mapper文件竟然不能够被springboot扫描到,导致在controller里面使用时出现装配异常。
2020-07-09 12:00:06.110 WARN 15848 --- [ main] ConfigServletWebServerApplicationContext :
Exception encountered during context initialization -
cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'userInfoController':
Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'com.example.demo.mapper.SysUserMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@javax.annotation.Resource(shareable=true, lookup=, name=, description=, authenticationType=CONTAINER, type=class java.lang.Object, mappedName=)}
2020-07-09 12:00:06.112 INFO 15848 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2020-07-09 12:00:06.128 INFO 15848 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-07-09 12:00:06.215 ERROR 15848 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean of type 'com.example.demo.mapper.SysUserMapper' that could not be found.
Action:
Consider defining a bean of type 'com.example.demo.mapper.SysUserMapper' in your configuration.
Process finished with exit code 1
直接垮掉
报这句注入有问题.
@Resource
private SysUserMapper sysUserMapper;
从网上查了springboot默认加载包:都说默认加载启动主类DemoApplication所在的包极其子包。
难道我这不算?明明是在同级包里面的鸭。
迫于无奈:只能换种方式曲线救国吧:
一、@Mapper注解
在SysUserMapper.java类名上加上@Mapper注解,可以在挨冻springboot时自动装配到容器里面。
@Mapper
public interface SysUserMapper extends MyMapper<SysUser> {
}
试一下:
成功了,果然好使嚎。
二、在启动类加上@MapperScan扫包注解
扫包注解直接添加mapper所在的包。
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
也没毛病了。扫包注解果然骚包。
不知道还有没有其他方法?或者说我的springboot配置不对?