国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

java - Spring使用@Autowired失效但是getBean()可以執(zhí)行成功

瀏覽:212日期:2023-12-20 10:53:41

問題描述

想整合一下mybatis和spring,讓UserMapper可以通過spring的方式自動(dòng)注入,但是不知道為什么在下面的代碼中通過getBean的方式可以成功得到UserMapper,但是通過@Autowire的方式卻無法實(shí)現(xiàn)依賴注入,請問錯(cuò)誤的原因可能有哪些?

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自動(dòng)注入的話會(huì)拋出NullPointerException,并且控制臺(tái)沒有輸出setterSystem.out.println(this.studentMapper.getById(1)); }}

mybatis-spring文檔地址

問題解答

回答1:

你這個(gè)單元測速的類,應(yīng)該沒放入Spring來管理吧

回答2:

TestSpringMybatis 加入spring @Component

回答3:

報(bào)什么錯(cuò),TestSpringMybatis 這個(gè)類是 spring 容器里面的嗎?@Resource?

回答4:

@Autowiredprivate userMapper mapper;

然后就可以在這個(gè)類里面直接用mapper了,不用再去set

標(biāo)簽: java
相關(guān)文章:
主站蜘蛛池模板: 淮安市| 永泰县| 仙居县| 贡嘎县| 普安县| 开远市| 顺义区| 旺苍县| 霍城县| 姚安县| 龙陵县| 涟源市| 平南县| 灵璧县| 五常市| 偏关县| 蓝田县| 亚东县| 和顺县| 堆龙德庆县| 都江堰市| 太仆寺旗| 沙河市| 浦东新区| 花莲县| 兴化市| 札达县| 云林县| 高平市| 潞城市| 沾化县| 聊城市| 宕昌县| 遵化市| 阿勒泰市| 灵武市| 宾阳县| 仲巴县| 嘉荫县| 阿勒泰市| 绵阳市|