springboot在工具類中添加service的方法,顯示為空的解決方案


@Component// 1、將工具類聲明為spring組件,這個必須不能忘

public class TestUtils {
//2、自動注入
@Autowired

private ItemService itemService;

 

// 3、靜態初使化當前類

public static TestUtils testUtils;

 

// 4、在方法上加上注解@PostConstruct,這樣方法就會在Bean初始化之后被Spring容器執行(注:Bean初始化包括,實例化Bean,並裝配Bean的屬性(依賴注入))。

@PostConstruct

public void init() {

testUtils = this;
testUtils.itemService = this.itemService;

}

 

// 5、utils工具類中使用service或mapper接口的方法例子,用"testUtils.xxx.方法" 就可以了

public static void test(Item record) {

// 6、調用service的方法

testUtils.itemService.insert(record);

}

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM