【问题标题】:Using @Qualifier based on @Inject field CDI使用基于 @Inject 字段 CDI 的 @Qualifier
【发布时间】:2016-03-07 13:43:22
【问题描述】:

我遇到了 CDI 条件问题 注入在EJB的注入中使用一种策略。

我的实际情况是:

public class someManagedBean {

    @Inject 
    @MyOwnQualifier(condition = someBean.getSomeCondition()) // not work because someBean is not already injected at this point
    private BeanInterface myEJB;

    @Inject
    SomeBean someBean;
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MyOwnQualifier {
    SomeCondition condition();
}

public class BeanInterfaceFactory {
    @Produces
    @MyOwnQualifier(condition = RoleCondition.ADMIN) 
    public BeanInterface getBeanInterfaceEJBImpl() {
        return new BeanInterfaceEJBImpl();
    }
}

public enum RoleCondition {
    ADMIN("ADMIN User");
}

好的,场景解释。现在的问题是我需要获得价值 从someBean.getSomeCondition() 返回一个RoleCondition,这是我的@MyOwnQualifier 所必需的。 但是此时 someBean 还没有被 CDI 注入。

我怎样才能使这条线工作?

@Inject 
@MyOwnQualifier(condition = someBean.getSomeCondition()) // not work because some is not already injected at this point
private BeanInterface myEJB;

如何使用基于另一个注入的属性值的限定符动态注入 bean?

【问题讨论】:

  • 我真的不明白这是如何工作的,因为注释是编译时的东西,并且 someBean.getSomeCondition() 在运行时进行评估。我更认为您想创建一个可以有条件地提供实例的生产者。 docs.jboss.org/weld/reference/1.0.0/en-US/html/…
  • 没有像beforeConstruct 这样的东西在尝试注入之前评估一些值吗?

标签: jakarta-ee ejb cdi qualifiers


【解决方案1】:

试试这个...

public class someManagedBean {

    @Inject 
    @MyOwnQualifier
    private BeanInterface myEJB;
}

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface MyOwnQualifier {
    SomeCondition condition();
}

public class BeanInterfaceFactory {

    @Inject
    SomeBean someBean

    @Produces
    @MyOwnQualifier
    public BeanInterface getBeanInterfaceEJBImpl() {
        if(someBean.getCondition()) {         
            return new BeanInterfaceEJBImpl();
        } else {
           ....
        }
    }
}

public enum RoleCondition {
    ADMIN("ADMIN User");
}

【讨论】:

  • 首先,感谢您的帮助。 someBean 出于某种原因此时在工厂 getBeanInterfaceEJBImpl 上为空
  • 如果为 null 表示 BeanInterfaceFactory 不是 cdi bean,请尝试添加 @Named。您在 beans.xml 中使用哪种发现模式?
  • 是的,对不起我的无知哈哈,午饭后我会检查是否一切正常,显然它会起作用。非常感谢,你是最棒的:)
  • 很高兴为您提供帮助! ;-)
  • 谢谢伙计,它就像一个魅力。我只需要将 new BeanInterfaceEJBImpl() 替换为 CDI.current().select(BeanInterfaceEJBImpl.class).get();
猜你喜欢
  • 2012-07-22
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 2011-05-07
  • 2017-11-08
  • 2018-09-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多