Dependency injection (IoC)
Dependency injection settings are completed by declaring @Inject
and @By
annotations on the class member attributes, and only class objects managed by the Bean container support dependencies. Injection, below is an example:
Example:
// 业务接口 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."; } }
Test code:
@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(); } } }