search

Home  >  Q&A  >  body text

java - 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文档地址

巴扎黑巴扎黑2783 days ago977

reply all(4)I'll reply

  • PHP中文网

    PHP中文网2017-04-18 10:58:42

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

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-18 10:58:42

    TestSpringMybatis join spring @Component

    reply
    0
  • PHPz

    PHPz2017-04-18 10:58:42

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

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:58:42

    @Autowired
    private userMapper mapper;

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

    reply
    0
  • Cancelreply