CDI @Produces with multiple properties files

筅森魡賤 提交于 2019-12-21 21:26:00

问题


Thanks to this post, https://stackoverflow.com/a/28047512/1227941 I am now using CDI to make msg available in my @Named beans like this:

@RequestScoped
public class BundleProducer {

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

With Injection like:

@Inject
private PropertyResourceBundle bundle;

The question: What should I do if I have more property files: ui.properties, admin.properties ...?


回答1:


I'd simply use a classifier annotation to choose which bundle to inject. Ripped from a little project of mine:

The annotation:

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

The producer method (adapt as necessary for your context):

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

And the injection:

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


来源:https://stackoverflow.com/questions/51819185/cdi-produces-with-multiple-properties-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!