加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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(被绑定类)上使用@act.inject.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;
}

链接

  • ActFramework依赖注入 I - 简介
  • ActFramework依赖注入 II - 注入对象类型
  • ActFramework官网
  • [ActFramework@开源中国](https://www.oschina.net/p/actframework)
  • [ActFramework@码云](https://git.oschina.net/actframework/actframework)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读