且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

读取托管 bean 中的资源包属性

更新时间:2021-10-23 01:53:46

假设你已经配置如下:

<resource-bundle>
    <base-name>com.example.i18n.text</base-name>
    <var>text</var>
</resource-bundle>

如果您的 bean 是请求范围的,您只需将 作为 @ManagedProperty 通过其 注入>:

If your bean is request scoped, you can just inject the <resource-bundle> as @ManagedProperty by its <var>:

@ManagedProperty("#{text}")
private ResourceBundle text;

public void someAction() {
    String someKey = text.getString("some.key");
    // ... 
}

或者如果您只需要一些特定的密钥:

Or if you just need some specific key:

@ManagedProperty("#{text['some.key']}")
private String someKey;

public void someAction() {
    // ... 
}

但是,如果您的 bean 处于更广泛的范围内,则在方法本地范围内以编程方式评估 #{text}:

public void someAction() {
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceBundle text = context.getApplication().evaluateExpressionGet(context, "#{text}", ResourceBundle.class);
    String someKey = text.getString("some.key");
    // ... 
}

或者如果您只需要一些特定的密钥:

Or if you only need some specific key:

public void someAction() {
    FacesContext context = FacesContext.getCurrentInstance();
    String someKey = context.getApplication().evaluateExpressionGet(context, "#{text['some.key']}", String.class);
    // ... 
}

您甚至可以通过标准的 ResourceBundle API 获取它,就像 JSF 本身已经在幕后做的那样,您只需要在代码中重复基本名称:


You can even just get it by the standard ResourceBundle API the same way as JSF itself is already doing under the covers, you'd only need to repeat the base name in code:

public void someAction() {
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceBundle text = ResourceBundle.getBundle("com.example.i18n.text", context.getViewRoot().getLocale());
    String someKey = text.getString("some.key");
    // ... 
}

或者,如果您通过 CDI 而不是 JSF 管理 bean,那么您可以为此创建一个 @Producer:

public class BundleProducer {

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

}

并注入如下:

@Inject
private PropertyResourceBundle text;

或者,如果您使用 JSF 实用程序库 OmniFacesMessages 类,那么您只需设置一次解析器即可让所有 Message 方法使用该包.


Alternatively, if you're using the Messages class of the JSF utility library OmniFaces, then you can just set its resolver once to let all Message methods utilize the bundle.

Messages.setResolver(new Messages.Resolver() {
    public String getMessage(String message, Object... params) {
        ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", Faces.getLocale());
        if (bundle.containsKey(message)) {
            message = bundle.getString(message);
        }
        return MessageFormat.format(message, params);
    }
});

另请参阅 javadoc 中的示例和展示页面.

See also the example in the javadoc and the showcase page.