美文网首页
java 静态工具类中注入service

java 静态工具类中注入service

作者: 莫名ypc | 来源:发表于2022-03-14 16:25 被阅读0次

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

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

相关文章

网友评论

      本文标题:java 静态工具类中注入service

      本文链接:https://www.haomeiwen.com/subject/iyqsdrtx.html