依賴注入(IoC)
透過在類別成員屬性上宣告@Inject
和@By
註解來完成依賴注入的設置,並且只有被Bean容器管理的類別物件才支援依賴注入,以下舉例說明:
範例:
// 业务接口 public interface IDemo { String sayHi(); } // 业务接口实现类1 @Bean public class DemoOne implements IDemo { public String sayHi() { return "Hello, YMP! I'm DemoOne."; } } // 业务接口实现类2 @Bean public class DemoTwo implements IDemo { public String sayHi() { return "Hello, YMP! I'm DemoTwo."; } }
測試程式碼:
@Bean public class TestDemo { @Inject private IDemo __demo1; @Inject @By(DemoOne.class) private IDemo __demo2; public void sayHi() { // _demo1注入的将是最后被注册到容器的IDemo接口实现类 System.out.println(__demo1.sayHi()); // _demo2注入的是由@By注解指定的DemoOne类 System.out.println(__demo2.sayHi()); } public static void main(String[] args) throws Exception { YMP.get().init(); try { TestDemo _demo = YMP.get().getBean(TestDemo.class); _demo.sayHi(); } finally { YMP.get().destroy(); } } }