@Autowired抱空指针异常解决方案

先给总结,再给实例

前提:

  类B里用了@Autowired注解,类A和类B都加了@Component或者其他形式如@Service这样都注解。

结果:

  如果类A 想访问类B,采用new B()的方式,则在类B里没法访问bean对象(也就是加了@Autowired的对象),会报空指针;

             如果在类A中注入类B,则在类B里可以访问注入的bean对象

原因:@Autowired注入即将对象注入到Spring的IOC容器内,而new出来的实例脱离了Spring的管理,两个对象不在一个管理者管理下,也即无法联系起来

举个最简单的例子: 

controller调用service,

@Controller
public class TestController {
    @Autowired
    TestService testService;
    @RequestMapping("/hello")
    public void getTest(){
        testService.sayHello();
        new TestServiceImpl().sayHello();
    }
}
@Service
public class TestServiceImpl implements TestService {
    @Autowired
    ApplicationContext ac;
    @Override
    public void sayHello() {
        System.out.println("----> " + ac);
        System.out.println("----> " + "hello world");
    }
}

看结果,一目了然

原文地址:https://www.cnblogs.com/qzhc/p/13681380.html