我有一个我正在构建的 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/