Here’s the scenario, create a custom JSF validator, injects a bean via Spring’s @Autowired. – Custom JSF validator
package com.mkyong.user;
import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
public class UsernameValidator implements Validator {
	UserService userService;
	public void validate(FacesContext context, UIComponent component,
		Object value) throws ValidatorException {
	  String username = value.toString();
		FacesMessage facesMsg = new FacesMessage("Username is duplicated");
		throw new ValidatorException(facesMsg);

In JSF / XHTML page, link it via validatorId.

<h:inputText id="username">
	<f:validator validatorId="usernameValidator" />


During application startup, log file shows that Spring is created the “UsernameValidator” bean, and UserService is injected successful.

However, when access from JSF page, the bean userService from “UsernameValidator” is showing null, caused a NullPointerException.


This is because @FacesValidator isn’t managed by Spring’s container. To fix it, reference the custom validator via binding, instead of validatorId.

P.S Spring, CDI and JSF, did a really bad job here (integrate each others), hope they can fix it in future release.

<h:inputText id="username">
	<f:validator binding="#{usernameValidator}" />

In custom validator class, uses Spring or CDI only, @FacesValidator is not necessary. – Spring Only
public class UsernameValidator implements Validator {
	UserService userService;
	//... – CDI Only
public class UsernameValidator implements Validator {
	UserService userService;

Of course, make sure Spring component auto scan is enabled.

<beans xmlns=""
	<context:component-scan base-package="com.mkyong" />
	<context:annotation-config />


  1. Named object not found
  2. JSF 2 custom validator example
Tags :
Founder of, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.
My website is hosted by Liquid Web, I really like their fast and helpful support, it saved me a lot of time. Furthermore, their servers are extremely reliable, fast and stable, I don't remember when was the last time we had server downtime. Btw, they're offering $100 Coupon now, if you are sourcing for great hosting provider, go grab it.

Related Posts

Popular Posts