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

想整合一下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文档地址

巴扎黑
巴扎黑

reply all(4)
Ty80

The class of your unit speed test should not be put into Spring for management

大家讲道理

TestSpringMybatis join spring @Component

PHPzhong

What error is reported? Is the TestSpringMybatis class in the spring container? @Resource?

黄舟

@Autowired
private userMapper mapper;

Then you can use mapper directly in this class without having to set it

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template