在项目中我们会多类的创建都会交给spring来完成。我们使用是都只要从容器中获取就可以了。
在某些情况下我们在自己建的类中会需要用到spring容器中的类,这样我们会写一个方法来获取,这个方法在这里就不做介绍了。有兴趣的可以看 https://blog.csdn.net/qq_34484062/article/details/101282262
我在项目中遇到过着样的情况,在 @Component 注解的类型中使用 SpringContextUtils.getBean() 方法来获取类。但是会报空指针异常。获取不到对应的类。
测试代码如下:
@Component
public class TestImpl {public void test(){System.out.println("方法测试");}
}
import org.springframework.stereotype.Component;
import zhong.test.springbootdemo.usultestdemo.demo.demo_1_Bean.SpringContextUtils;/*** 测试 @Component注解的类中 有 SpringContextUtils.getBean() 获取的类的问题。*/
@Component
public class ComponentTest{public TestImpl test = SpringContextUtils.getBean(TestImpl.class);public void run(){test.test();}
}
然后使用接口测试:
@SpringBootApplication(scanBasePackages = "zhong.test.springbootdemo.usultestdemo")
@RestController
public class UsulTestStartApplication {@AutowiredComponentTest componentTest;public static void main(String[] args) {SpringApplication.run(UsulTestStartApplication.class, args);}@GetMapping(value="/test")public void test(){componentTest.run();}}
打断点看结果:
可以看到没有获取到结果。
我们将 ComponentTest上的@Component去掉,在外层使用new的方式来获取ComponentTest对象在调用的方法。
@GetMapping(value="/test")public void test(){ComponentTest componentTest = new ComponentTest();componentTest.run();}
结果如图:
可以看到这样是能获取到TestImpl对象的。
原因,我没有去深究。个人认为这个是使用@Component注解的对象是在 SpringContextUtils中的ApplicationContext对象被实例化加载之前就已经加载了。所以并不能从SpringContextUtils.getBean()中获取到对象。
当然这个是我的猜测,具体是不是,等以后在研究。
有什么错误的地方,欢迎指正,谢谢。