如何从java代码访问消息包以根据当前区域设置获取消息?
我尝试使用@ManagedProperty如下:
@Named
@SessionScoped
public class UserBean implements Serializable {
@ManagedProperty("#{msg}")
private ResourceBundle bundle;
// ...
public void setBundle(ResourceBundle bundle) {
this.bundle = bundle;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,它仍然存在null.它似乎在一个内部不起作用@Named.
这是我在faces-context.xml以下方面注册资源包的方式:
<application>
<message-bundle>validator.messages</message-bundle>
<locale-config>
<supported-locale>en_US</supported-locale>
<supported-locale>ua_UA</supported-locale>
</locale-config>
<resource-bundle>
<base-name>lang.messages</base-name>
<var>msg</var>
</resource-bundle>
</application>
Run Code Online (Sandbox Code Playgroud)
作者的作者:
@BalusC我收到错误
16:29:10,968 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/WEBSearchPrime_JB_lang].[Faces Servlet]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet Faces Servlet threw exception: org.jboss.weld.exceptions.IllegalProductException: WELD-000054 Producers cannot produce non-serializable instances for injection into non-transient fields of passivating beans\\n\\nProducer\: Producer Method [PropertyResourceBundle] with qualifiers [@Any @Default] declared as [[method] @Produces public util.BundleProducer.getBundle()]\\nInjection Point\: [field] @Inject private model.UserBean.bundle
注意,我也把Serializable接口
您不能@ManagedProperty在CDI托管bean中使用注释@Named.您只能在带有注释的JSF托管bean中使用它@ManagedBean.
CDI没有任何注释来注入EL表达式的评估结果,如as @ManagedProperty.该CDI的方法是使用一个"CDI生产者"与@Produces其中返回的具体类型,这是PropertyResourceBundle在的情况下,.properties基于文件的资源包.
只需将此类放在WAR中的某个位置:
@RequestScoped
public class BundleProducer {
@Produces
public PropertyResourceBundle getBundle() {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().evaluateExpressionGet(context, "#{msg}", PropertyResourceBundle.class);
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以按如下方式注入它:
@Inject
private PropertyResourceBundle bundle;
Run Code Online (Sandbox Code Playgroud)