zoukankan      html  css  js  c++  java
  • @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");
        }
    }

    看结果,一目了然

  • 相关阅读:
    Linux启动mysql命令
    Linux启动Apache服务器命令
    使用SSH命令从一台Linux远程登陆到另一台Linux
    Linux关机命令
    从Windows复制文件到Linux
    无法访问SVN历史记录的问题
    linux静态IP最简配置
    学习之Redis(二)
    学习之Redis(一)
    MySQL数据库笔记总结
  • 原文地址:https://www.cnblogs.com/qzhc/p/13681380.html
Copyright © 2011-2022 走看看