6

Possible Duplicate:
Dependency injection in FacesValidator (JSF Validation)

Maybe, I'm missing something basic - but can't I use injection in a custom validator class in order to use the message resources? The following code gives me a null on msg, so injection obviously does not work, but why? And if it's not possible, how can I access the message resources? All examples I found so far, use hard coded text in validator messages which is not very useful for localization.

public class BirthdateValidator implements Validator {
    @Inject
    private transient ResourceBundle msg;

    @Override
    public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
            if ( [some validation fails] ) {
                FacesMessage message = new FacesMessage(msg.getString("validator.birthday"));
                message.setSeverity(FacesMessage.SEVERITY_ERROR);
            }
    }
}
Community
  • 1
  • 1
Alexander Rühl
  • 6,769
  • 9
  • 53
  • 96
  • I saw this post in the search result I did before posting, but the main tag "spring" let me skip it. - Ok since I only need to access the message bundle, how would I access it without injection? That way I could avoid changing all occurrences of all my validators. – Alexander Rühl Jan 21 '13 at 12:24

1 Answers1

10

As to why it doesn't work that way, see this answer: How to inject in @FacesValidator with @EJB, @PersistenceContext, @Inject, @Autowired. In a nutshell, annotate it @Named instead of @FacesValidator and reference it in <h:inputXxx validator> or <f:validator binding> as #{birthdateValidator} instead. The problem is caused by an oversight by JSF/CDI guys. This is fixed in upcoming JSF 2.2.


Ok since I only need to access the message bundle, how would I access it without injection?

Evaluate it programmatically using Application#evaluateExpressionGet():

ResourceBundle msg = context.getApplication().evaluateExpressionGet(context, "#{msg}", ResourceBundle.class);
// ...

You can even pick a specific key:

String msg = context.getApplication().evaluateExpressionGet(context, "#{msg.key}", String.class);
// ...

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555