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. angular.js - ng-grid 和tabset一起用时,grid width默认特别小2. python for循环中的函数只能运行一次?3. javascript - Vue.js2.0不能使用debounce后大伙一般是如何解决延迟请求的问题的呢。4. html5 - 在一个页面中 初始了两个swiper 不知道哪里错了 一直不对5. selenium-基于python2-126邮箱登陆问题6. python的文件读写问题?7. css - transform-origin 旋转参考点8. python - pyspider爬取了接近1G的数据,无法导出csv?9. android - 美团筛选处筛选条件停靠+条件点击滑动到顶部。10. 请问是对象还是数组
