在ActFramework 依赖注入 II - 注入对象类型中我们提到了定义绑定的一种方式:
// 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的其他绑定方式
工厂和上面的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;
}
}
自动绑定不需要定义Module和工厂,但是需要在Interface(被绑定类)上使用@AutoBind
注解:
// 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");}
}
使用@javax.inject.Named
注解定义Qualified的实现
// 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;
}