jsf - 在 ManagedProperty 中使用 ResourceBundle 中的属性

标签 jsf jsf-2 resourcebundle postconstruct

我有一个我正在构建的 JSF 验证器,其中包含我想从 ResourceBundle 加载的属性。但是,我不太确定如何工作,因为它没有正确加载。关于如何完成这项工作的任何想法?

我试过使用 @PostContruct这样做,但我在 Eclipse 中收到以下错误:

Access restriction: The type PostConstruct is not accessible due to restriction on required library /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Classes/classes.jar



所以,我不太确定最好的方法是什么。我正在谈论的示例如下...

验证器...
@FacesValidator("usernameValidator")
public class UserNameValidator implements Validator {

  @ManagedProperty(value="#{props_userNamePattern}")
  private String userNamePattern;  

  @ManagedProperty(value="#{props_minUserNameLength}")
  private int minUserNameLength;  

  @ManagedProperty(value="#{props_maxUserNameLength}")
  private int maxUserNameLength;

  public void validate(FacesContext context, UIComponent component, Object
        value) throws ValidatorException {
    //My validations here...   
  }

  //Setters for the class properties

}

faces-config.xml
<resource-bundle>
    <base-name>settings</base-name>
</resource-bundle>

设置.属性
props_userNamePattern = /^[a-z0-9_-]+$/
props_minUserNameLength = 3
props_maxUserNameLength = 30

最佳答案

@ManagedProperty 适用于 @ManagedBean 只上课。 @PostConstruct 也不会是您功能需求的正确解决方案。它旨在放置在一个方法上,该方法将在构建类并且完成所有依赖注入(inject)时执行。您面临的错误是由旧 Eclipse+JRE 版本的特定组合引起的。如果升级不是一个选项,您可以通过 Window > Preferences > Java > Compiler > Errors/Warnings > Deprecated and restricted API > Forbidden reference > Ignore 禁用警告/错误。

至于您的功能要求,不幸的是没有任何注释可以实现这一点。但是,您可以通过编程方式获得它。

String bundlename = "settings";
Locale locale = FacesContext.getCurrentInstance().getViewRoot().getLocale();
ResourceBundle bundle = ResourceBundle.getBundle(bundlename, locale);
String usernamePattern = bundle.getString("props_userNamePattern");
// ...

您可以在验证器的构造函数中执行此操作。如果使用得当,无论如何都会为每个 View 创建一个新实例。

关于jsf - 在 ManagedProperty 中使用 ResourceBundle 中的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5622439/

相关文章:

java - IntelliJ : Adding resources to the class path, 但仍然给我 "java.util.MissingResourceException: Can' t 查找包....区域设置 en_US”

java - 类加载器在加载资源包中的意义

java - 通过netbeans在tomcat服务器上部署应用

javascript - 如何在 JSF 上使用 Markdown 编辑器 - Primefaces

jsf - javax.el.PropertyNotFoundException : The class 'xxx' does not have a readable property 'yyy'

javascript - 使用 h :selectBooleanCheckbox 显示/隐藏另一个输入字段

javascript JSON 对象到 JSF back bean

javascript - 使用 primefaces 中的 javascript 从 selectOnemenu 获取选定值并打开一个对话框

spring - ViewScoped Bean 导致 NotSerializableException

visual-studio - 是否可以将自定义资源类型添加到 .NET .resx 文件?