java 静态工具类中注入service

2022-03-14  本文已影响0人  莫名ypc

有时我们需要在一个工具类中使用@Autowired 注解注入一个service,但是由于工具类方法都是直接调用,所以一般都写成static,因此直接属性注入就存在问题。
使用如下方式在set方法上注入可以解决:

@Component
public class TestUtil {
 
    private static TestService testService;
 
    @Autowired
    public void setTestService(TestService testService){
        TestUtil.testService = testService;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读