且构网

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

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

更新时间:2021-10-13 02:23:23

假定您已按照以下方式进行配置:

Assuming that you've configured it as follows:

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

如果您的bean是请求范围的,则可以通过<var><resource-bundle>注入为@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实用程序库 OmniFaces Messages类,则只需设置它的解析器一次,以允许所有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.