gpt4 book ai didi

jsf - 通过@ManagedProperty 注入(inject)ResourceBundle 似乎在@Named 中不起作用

转载 作者:行者123 更新时间:2023-12-01 07:55:38 25 4
gpt4 key购买 nike

如何从 java 代码访问消息包以根据当前语言环境获取消息?
我尝试使用 @ManagedProperty如下所示:

@Named 
@SessionScoped
public class UserBean implements Serializable {

@ManagedProperty("#{msg}")
private ResourceBundle bundle;

// ...

public void setBundle(ResourceBundle bundle) {
this.bundle = bundle;
}

}
但是,它仍然是 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>
作者更新:
我收到错误 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 接口(interface)

最佳答案

您不能使用 @javax.faces.bean.ManagedProperty 在使用 @Named 注释的 CDI 托管 bean 中.您只能在带有 @ManagedBean 注释的 JSF 托管 bean 中使用它。 .

您需要使用 @javax.faces.annotation.ManagedProperty 相反,连同 @Inject .这是在 JSF 2.3 中引入的。

@Inject @javax.faces.annotation.ManagedProperty("#{msg}")
private ResourceBundle bundle;

应该注意的是,这将作为 @Dependent 注入(inject)。 .因此请注意,当您将其注入(inject) @SessionScoped 时bean,那么它基本上会变成 @SessionScoped也因此永远坚持最初注入(inject)的值(value)。因此, session 后期任何潜在的语言环境更改都不会反射(reflect)在那里。如果这是一个拦截器,那么你真的应该将它注入(inject)到 @RequestScoped 中。或 @ViewScoped仅,或使用 @Producer如下所示。

CDI 没有 native 注释来注入(inject) EL 表达式的评估结果。 CDI 方法是使用带有 @Produces 的“CDI 生产者”。其中返回具体类型,即 PropertyResourceBundle如果是 .properties基于文件的资源包。

因此,如果您无法升级到 JSF 2.3,那么只需将此类放在 WAR 中的某个位置:
@RequestScoped
public class BundleProducer {

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

}

有了这个,可以如下注入(inject):
@Inject
private PropertyResourceBundle bundle;

关于jsf - 通过@ManagedProperty 注入(inject)ResourceBundle 似乎在@Named 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28045667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com