java - Spring使用@Autowired失效但是getBean()可以执行成功
问题描述
想整合一下mybatis和spring,让UserMapper可以通过spring的方式自动注入,但是不知道为什么在下面的代码中通过getBean的方式可以成功得到UserMapper,但是通过@Autowire的方式却无法实现依赖注入,请问错误的原因可能有哪些?
public class TestSpringMybatis { private UserMapper userMapper; @Autowired @Qualifier('userMapper') public void setStudentMapper(UserMapper userMapper) {System.out.println('setter');this.userMapper = userMapper; }@Test public void getUser() {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();applicationContext.register(AppConfig.class);applicationContext.refresh();// 通过getBean的方式执行成功UsreMapper u = (UserMapper)applicationContext.getBean('userMapper');System.out.println(u.getById(1));// 但是通过@Autowired自动注入的话会抛出NullPointerException,并且控制台没有输出setterSystem.out.println(this.studentMapper.getById(1)); }}
mybatis-spring文档地址
问题解答
回答1:你这个单元测速的类,应该没放入Spring来管理吧
回答2:TestSpringMybatis 加入spring @Component
回答3:报什么错,TestSpringMybatis 这个类是 spring 容器里面的吗?@Resource?
回答4:@Autowiredprivate userMapper mapper;
然后就可以在这个类里面直接用mapper了,不用再去set
相关文章:
1. javascript - angularjs怎么获取repeat里的某些$index值?2. html5和Flash对抗是什么情况?3. java - spring-security与微信登录的问题?4. html5 - iphone5手机,微信中无法打开优酷链接?5. javascript - 移动端,当出现遮罩层的时候,遮罩层里有div是超出高度scroll的,怎么避免滑动div的时候,body跟随滑动?6. docker-compose 为何找不到配置文件?7. 用Java8的 stream 操作外部集合是否存在并发问题?8. css3 - 请问,如何写这个颜色的(渐变),并且在移动端自适应9. javascript - 求解答:实例对象调用constructor,此时constructor内的this的指向?10. MySQL启动错误
