成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

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

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

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

問題描述

想整合一下mybatis和spring,讓UserMapper可以通過spring的方式自動注入,但是不知道為什么在下面的代碼中通過getBean的方式可以成功得到UserMapper,但是通過@Autowire的方式卻無法實(shí)現(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:

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

回答4:

@Autowiredprivate userMapper mapper;

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

標(biāo)簽: java
相關(guān)文章: