【问题标题】:CDI @Produces with multiple properties filesCDI @Produces 具有多个属性文件
【发布时间】:2019-01-19 23:57:31
【问题描述】:

感谢这篇文章,https://stackoverflow.com/a/28047512/1227941 我现在使用 CDI 在我的 @Named bean 中提供 msg,如下所示:

@RequestScoped
public class BundleProducer {

@Produces
public PropertyResourceBundle getBundle() {
    FacesContext context = FacesContext.getCurrentInstance();
    return context.getApplication().evaluateExpressionGet(context, "#{msg}", PropertyResourceBundle.class);
    }
}

像注入一样:

@Inject
private PropertyResourceBundle bundle;

问题:如果我有更多的属性文件怎么办:ui.properties,admin.properties...?

【问题讨论】:

  • 我个人尽量减少 messageBundles 的数量并使用“复合键”(ui.xxx,admin.yyy)不知道这是否是最佳实践,但它对我有用
  • 我也在寻找关于这一点的最佳实践
  • 首先,我建议您生成ResourceBundle 而不是特定的PropertyResourceBundle。然后,您可以使用 CDI 限定符来区分各种捆绑包。

标签: jsf cdi inject resourcebundle


【解决方案1】:

我只需使用分类器注释来选择要注入的包。摘自我的一个小项目:

注释:

@Qualifier
@Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface Bundle {
   @Nonbinding
   public String value() default "";
}

生产者方法(根据您的上下文进行调整):

@Produces @Bundle ResourceBundle loadBundle(InjectionPoint ip) {
     String bundleName = ip.getAnnotated().getAnnotation(Bundle.class).value();
     ResourceBundle res = ResourceBundle.getBundle(bundleName);
     return res;
}

还有注射:

@Inject @Bundle("ui")
private ResourceBundle uiResources;

【讨论】:

  • 酷,简单而灵活。
  • @mtj 我有以下异常:Exception during lifecycle processing org.glassfish.deployment.common.DeploymentException: CDI deployment failure:WELD-001408: Unsatisfied dependencies for type ResourceBundle with qualifiers @Bundle at injection point [BackedAnnotatedField] @Inject @Bundle private com.mypckage.MyBean.uiResources任何帮助请
  • @Hicham 你能按现在的样子发布代码吗?
  • 包接口package com.locale; 987654326 import java.lang.annotation.Retention; 987654328 import java.lang.annotation.Target; 987654330 import javax.inject.Qualifier; 987654332 @Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) 987654334 public atinterface Bundle {`@ Nonbinding``公共字符串值() 默认 "";` }
  • BundleProducer package com.locale; import java.util.ResourceBundle; import javax.enterprise.inject.Produces; import javax.enterprise.inject.spi.InjectionPoint; public class BundleProducer { atProduces atBundle public ResourceBundle loadBundle(InjectionPoint ip) { String bundleName = ip.getAnnotated().getAnnotation(Bundle.class).value(); ResourceBundle res = ResourceBundle.getBundle(bundleName); return res; } } 使用 ResourceBundle @Inject @Bundle("user") private BundleProducer uiResources;
猜你喜欢
  • 1970-01-01
  • 2023-03-10
  • 2016-01-03
  • 2020-06-23
  • 2023-03-04
  • 2018-01-11
  • 1970-01-01
  • 2023-03-27
  • 2012-05-13
相关资源
最近更新 更多