java - Spring使用@Autowired失效但是getBean()可以執(zhí)行成功
問題描述
想整合一下mybatis和spring,讓UserMapper可以通過spring的方式自動注入,但是不知道為什么在下面的代碼中通過getBean的方式可以成功得到UserMapper,但是通過@Autowire的方式卻無法實現(xiàn)依賴注入,請問錯誤的原因可能有哪些?
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的方式執(zhí)行成功UsreMapper u = (UserMapper)applicationContext.getBean('userMapper');System.out.println(u.getById(1));// 但是通過@Autowired自動注入的話會拋出NullPointerException,并且控制臺沒有輸出setterSystem.out.println(this.studentMapper.getById(1)); }}
mybatis-spring文檔地址
問題解答
回答1:你這個單元測速的類,應(yīng)該沒放入Spring來管理吧
回答2:TestSpringMybatis 加入spring @Component
回答3:報什么錯,TestSpringMybatis 這個類是 spring 容器里面的嗎?@Resource?
回答4:@Autowiredprivate userMapper mapper;
然后就可以在這個類里面直接用mapper了,不用再去set
相關(guān)文章:
1. c++ - 如何正確的使用QWebEngineView?2. javascript - js 寫一個正則 提取文本中的數(shù)據(jù)3. WEB-INF / classes /與WEB-INF / lib / *。jar在類路徑優(yōu)先級?4. javascript - 關(guān)于Lazyload遇到的問題5. 算法 - python 給定一個正整數(shù)a和一個包含任意個正整數(shù)的 列表 b,求所有<=a 的加法組合6. ruby - gitlab托管,git clone 失敗?7. yii2中restful配置好后在nginx下報404錯誤8. angular.js - react的redux和vue的vuex,angular呢9. java - 我在用Struts2上傳文件時,報以下錯誤怎么回事?10. javascript - 游戲里物體角色層次渲染邏輯和代碼怎么寫才好?
