【问题标题】:Passing parameter to bean using CDI使用 CDI 将参数传递给 bean
【发布时间】:2013-10-14 20:14:56
【问题描述】:

我是 CDI 的新手。我不知道如何使用 CDI 转换以下代码。

Class Client {

  void method(){
    List<Events> events = getEvents();
    I b = new B(events); 
    I c = new C("Hello"); 
  }

 List<Events> getEvents(){
    //Do Something 
    return events;
  }
}

Class B implements I{

 List<Events> events ;

 B(List<Events> events){
    this.events = events; 
  }
}

Class C implements I{

 String s;
  C(String s){
    this.s = s; 
  }
}

我使用限定符来避免歧义,但可以弄清楚如何从客户端传递参数。是否需要使用生产者将列表和字符串分别注入 B 类和 C 类?

@Qualifier
@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface Ii {
Type value() ;
public enum Type {
      B,
      C 
  }

}


Class Client {
   @Inject @Ii(Ii.type.B)
   B b;
   @Inject @Ii(Ii.type.C)
   C b;

}

@Ii(Ii.type.B)
Class B { 

}

@Ii(Ii.type.C)
Class C {
}

【问题讨论】:

    标签: jakarta-ee cdi


    【解决方案1】:

    您需要声明一个生产者。

    @Produces @Ii(Ii.type.B)
    public void produceB {
      return Ii.type.B;
    }
    
    @Produces @Ii(Ii.type.C)
    public void produceC {
      return Ii.type.C;
    }
    

    为了您的事件,您需要使用@Observes 注释应该创建事件的参数。在下面的代码中,您可以看到如何获取已触发事件的列表。

    @Inject
    private List<Event> events;
    

    【讨论】:

    • 但是B类怎么会得到List呢? Produces 只会返回 new B()。
    • 我用允许您访问事件列表的代码更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多