久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

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

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

瀏覽:205日期: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
相關文章:
主站蜘蛛池模板: 鄂温| 娄烦县| 鹰潭市| 呼图壁县| 镇巴县| 蚌埠市| 广昌县| 怀化市| 福建省| 弥勒县| 海南省| 遵化市| 安岳县| 固安县| 菏泽市| 广元市| 讷河市| 尉氏县| 华蓥市| 永平县| 务川| 北宁市| 砀山县| 尉氏县| 开封市| 邵阳市| 南城县| 平舆县| 新龙县| 镇雄县| 巴东县| 东源县| 林州市| 屯留县| 合作市| 罗田县| 长兴县| 苗栗市| 镇宁| 高密市| 保德县|