2

The Following code works, what I need to know is that, is there a way to inject the an EJB (or ManagedBean) using an annotations (Such as @EJB, @Inject, @Resource)

public class UniqueUsernameConstraintValidator implements ConstraintValidator<UniqueUsername, String> {

//TODO research on how to inject an EJB/BusinessObject (@EJB does not work)
private JournalBean bean;

@Override
public void initialize(UniqueUsername annotation) {
//This is a fall back there must be a better way
    try {
        javax.naming.Context context = new InitialContext();
        bean = (JournalBean)context.lookup("java:global/Journal2/JournalBean");
    } catch (NamingException e) {
        logger.info("NamingException: " + e.getMessage());
    }
}

public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
    return false;
}

if (null == bean.getUserByUsername(value)) {
    return true;
}
    return false;
}
}

The following code does NOT work (variable logic is never initialized - null), I do have an empty beans.xml file in the WEB-INF directory. When I use @Inject in a in a ManagedBean, Servlet or EJB directly then it works

public class UniqueUsernameConstraintValidator implements ConstraintValidator<UniqueUsername, String> {

@Inject
private Journal logic;

@Override
public void initialize(UniqueUsername annotation) {
    logger.info("initialize("+annotation+")");
}

@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
    if (value == null) {
        return false;
    }

    logger.warning("TODO: IMPLEMENT VALIDATION");   
    try {
        if (null != logic.getUserByUsername(value)) { //Null
            return true;
        }
    } catch (EntityAccessorException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
    }
}

Is there a way to make this work?

Jan Groth
  • 14,039
  • 5
  • 40
  • 55
Hlulani
  • 419
  • 4
  • 12

2 Answers2

0

It doesn't work out of the box, but is easily achievable buy bridging Hibernate Bean Validation to CDI.

Check that answer on an almost identical question.

Community
  • 1
  • 1
Jan Groth
  • 14,039
  • 5
  • 40
  • 55
0

The idea is to write your custom (injection enabled) ConstraintValidatorFactory which then handles the injections into the ConstraintValidator instances. As in the answer mentioned above the Seam-Validation module is a good place to see how it is done.

In Bean Validation 1.1 container (CDI) integration will be part of the specification. See http://beanvalidation.org/proposals/BVAL-238/

Hardy
  • 18,659
  • 3
  • 49
  • 65