ActFramework 依赖注入 III - 定义绑定
发布时间:2020-12-14 01:50:49 所属栏目:百科 来源:网络整理
导读:在ActFramework 依赖注入 II - 注入对象类型中我们提到了定义绑定的一种方式: 1. 使用Module // Define bindingspublic class MyModule extends org.osgl.inject.Module { protected void configure() { bind(MyService.class).to(OneService.class); bind(M
在ActFramework 依赖注入 II - 注入对象类型中我们提到了定义绑定的一种方式: 1. 使用Module// Define bindings public class MyModule extends org.osgl.inject.Module { protected void configure() { bind(MyService.class).to(OneService.class); bind(MyService.class).named("two").to(TwoService.class); } } 这篇文章继续介绍ActFramework的其他绑定方式 2. 自定义工厂工厂和上面的Module是相当的,把上面的Module用工厂的方式来写会是这样: public class MyFactory { @org.osgl.inject.annotation.Provides public MyService getOneService(OneService oneService) { return oneService; } @org.osgl.inject.annotation.Provides @Named("two") public MyService getTwoService(TwoService twoService) { return twoService; } } 3. 自动绑定自动绑定不需要定义Module和工厂,但是需要在Interface(被绑定类)上使用 // The interface @act.inject.AutoBind public interface MyService { void service(); } 定义缺省实现 // The implemention one public class OneService implements MyService { public void service() {Act.LOGGER.info("ONE is servicing");} } 使用 // The implemention two @javax.inject.Named("two") public class TwoService implements MyService { public void service() {Act.LOGGER.info("TWO is servicing");} } 使用依赖注入 // Inject the service public class Serviced { // this one will get bind to the default implementation: OneService @javax.inject.Inject private MyService one; // this one will get bind to TwoService @javax.inject.Inject @javax.inject.Named("two") private MyService two; } 链接
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |