工具类使用@autowired注入service为null空

欧阳小白 1年前 ⋅ 745 阅读
@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处理。


全部评论: 0

    我有话说:

    咨询问题

    点击这里给我发消息

    淘宝咨询

    博主承接代做业务

    真·送云服务器

    咨询博主