java - Spring使用@Autowired失效但是getBean()可以执行成功
巴扎黑
巴扎黑 2017-04-18 10:56:42
0
4
928

想整合一下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,并且控制台没有输出setter
        System.out.println(this.studentMapper.getById(1));
    }
}

mybatis-spring文档地址

巴扎黑
巴扎黑

全部回覆(4)
Ty80

你這個單元測速的類,應該沒放入Spring來管理吧

大家讲道理

TestSpringMybatis 加入spring @Component

PHPzhong

報什麼錯,TestSpringMybatis 這個類別是 spring 容器裡面的嗎? @Resource?

黄舟

@Autowired
private userMapper mapper;

接著就可以在這個類別裡面直接用mapper了,不用再去set

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!