Spring注入service为null另类解决办法 工具类 一般类 静态 非controller

    xiaoxiao2021-03-25  134

    系统为SpringMVC框架,在开发的过程中有一些工具类需要调用下由spring管理的service层。但是一进注入不进来,报null异常; 在尝试了网上的一系列方法后,还是没有解决。网上的解决方法主要有以下几种: 1、将工具类申明为spring组件,如@controller @compent 等,在spring自动扫描包设置中将工具类所在的包加进来; 无效 2、new一个service; 无效 而且不符合spring管理;

    最后解决方法如下:

    @Component //申明为spring组件 public class TestUtils { @Autowired private TestService testService; //添加所需service的私有成员 private static TestUtils testUtils ; // 关键点1 静态初使化 一个工具类 这样是为了在spring初使化之前 public void setTestService(TestService testService) { this.testService = testService; } @PostConstruct //关键二 通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作 public void init() { testUtils = this; testUtils.testService = this.testService; // 初使化时将已静态化的testService实例化 } } 这样下面的代码中就可以通过 testUtils.testService 来调用service处理 转载自http://www.cnblogs.com/allforone/p/4108862.html,非常好用,我记录一下。
    转载请注明原文地址: https://ju.6miu.com/read-9703.html

    最新回复(0)