在非Controller中@Autowired注解变量

当在非Controller要自动注解变量,尤其是static变量时会在运行时报出空指针的错误。我就遇到了这种情况,后来在网上查了许多后,总结基本上有这种情况可以解决。

@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处理

我是没有用这种方法,大家可以试一试。
这里我介绍一下我自己的方法,我使用SpringContectHolder类将用到的类的class读入让后再调用类中方法解决的

private static JiamgsMapper jiamgsMapper = SpringContextHolder.getBean(JiamgsMapper.class);
posted @ 2018-07-27 10:23  聆听*幸福  阅读(320)  评论(0编辑  收藏  举报