title: Bean Validation: custom validation against the database
body: <p>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)</p>
  
  <pre><code>public class UniqueUsernameConstraintValidator implements ConstraintValidator&lt;UniqueUsername, String&gt; {
  
  //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;
  }
  }
  </code></pre>
  
  <p>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</p>
  
  <pre><code>public class UniqueUsernameConstraintValidator implements ConstraintValidator&lt;UniqueUsername, String&gt; {
  
  @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;
      }
  }
  </code></pre>
  
  <p>Is there a way to make this work?</p>