您的位置:首頁技術文章
文章詳情頁

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

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

問題描述

想整合一下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

標簽: java
相關文章:
国产综合久久一区二区三区