问题描述
如何从Java代码访问消息束以根据当前语言环境获取消息?
How can I access messages bundle from java code to get message according to current locale?
我尝试使用@ManagedProperty
,如下所示:
I tried using @ManagedProperty
like below:
@Named
@SessionScoped
public class UserBean implements Serializable {
@ManagedProperty("#{msg}")
private ResourceBundle bundle;
// ...
public void setBundle(ResourceBundle bundle) {
this.bundle = bundle;
}
}
但是,它仍然是null
.似乎在@Named
内不起作用.
However, it remains null
. It seems that it doesn't work inside a @Named
.
这是我在faces-context.xml
中注册资源束的方式:
This is how I registered the resource bundle in 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>
作者评论:
udated by author:
@BalusC我收到错误消息
@BalusC I get error
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接口
note, that I also put Serializable interface
推荐答案
您不能在CDI托管Bean中使用@ManagedProperty
进行@Named
注释.您只能按@ManagedBean
注释在JSF托管bean中使用它.
You can't use @ManagedProperty
in a CDI managed bean as annotated with @Named
. You can only use it in a JSF managed bean as annotated with @ManagedBean
.
CDI没有任何注解来插入像@ManagedProperty
这样的EL表达式的评估结果. CDI方法是使用带有@Produces
的"CDI生产者",其中您返回具体类型,对于基于.properties
文件的资源包,该类型为PropertyResourceBundle
.
CDI doesn't have any annotations to inject the evaluation result of an EL expression like as @ManagedProperty
. The CDI approach is using a "CDI producer" with @Produces
wherein you return the concrete type, which is PropertyResourceBundle
in case of .properties
file based resource bundles.
只需将此类放在您的WAR中:
Just drop this class somewhere in your WAR:
@RequestScoped
public class BundleProducer {
@Produces
public PropertyResourceBundle getBundle() {
FacesContext context = FacesContext.getCurrentInstance();
return context.getApplication().evaluateExpressionGet(context, "#{msg}", PropertyResourceBundle.class);
}
}
现在您可以按如下方式注入它:
Now you can inject it as below:
@Inject
private PropertyResourceBundle bundle;
这篇关于通过@ManagedProperty注入ResourceBundle似乎在@Named内部不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!