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);

}

}
原文地址:https://www.cnblogs.com/dhrwawa/p/11004645.html