Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injection in custom validator [duplicate]

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);
            }
    }
}
like image 384
Alexander Rühl Avatar asked Jan 21 '13 11:01

Alexander Rühl


1 Answers

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:

  • Read resource bundle properties in a managed bean
like image 148
BalusC Avatar answered Sep 18 '22 05:09

BalusC