依赖注入(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(); } } }