Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
244 views
in Technique[技术] by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

TestSpringMybatis 加入spring @Component


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...