创建自定义Java注入注释

时间:2018-12-12 10:52:25

标签: java dependency-injection annotations singleton

出于学习目的,我想创建两个自定义Java注释:

  • @SingletonBean将类转换为Singleton
  • @InjectBean在需要的地方注入单例实例。

这意味着如果我写:

@SingletonBean
public class Engine{ ... }

public class Car {
   @InjectBean Engine engine;
   ...
}

我希望在实际情况下,这是完全等效的:

public class Engine{
   private static Engine instance;
   public static Engine getInstance(){
      if(instance==null){
         instance = new Engine();
      }
      return instance;
   }
   ...
}


public class Car {
   Engine engine = Engine.getInstance();
   ...
}

如何定义两个注释和相应的行为?

0 个答案:

没有答案