加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

工具类如何使用依赖注入其他组件

发布时间:2020-12-14 02:01:05 所属栏目:百科 来源:网络整理
导读:@Component //申明为spring组件 public class TestUtils { @Autowired private TestService testService; //添加所需service的私有成员 //关键点一 静态初使化一个工具类,这样是为了在spring初使化之前 private static TestUtils testUtils ; public void s
@Component     //申明为spring组件 
public class TestUtils {    
    @Autowired      
    private TestService testService;  //添加所需service的私有成员
    //关键点一 静态初使化一个工具类,这样是为了在spring初使化之前
    private static TestUtils  testUtils ;  

    public void setTestService(TestService  testService) {    
        this.testService = testService;    
    }    

    //关键点二 通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
    @PostConstruct     
    public void init() {
        testUtils = this;    
        testUtils.testService = this.testService;   // 初使化时将已静态化的testService实例化 
    }

这样下面的代码中就可以通过 testUtils.testService 来调用service处理。

鸣谢:all_forone

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读