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

@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

相关文章

迭代器模式(Iterator)迭代器模式(Iterator)[Cursor]意图...
高性能IO模型浅析服务器端编程经常需要构造高性能的IO模型,...
策略模式(Strategy)策略模式(Strategy)[Policy]意图:定...
访问者模式(Visitor)访问者模式(Visitor)意图:表示一个...
命令模式(Command)命令模式(Command)[Action/Transactio...
生成器模式(Builder)生成器模式(Builder)意图:将一个对...