非controller,非service注入

系統爲SpringMVC框架,在開發的過程中有一些工具類需要調用下由spring管理的service層。

 

@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處理。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章