以下代码有效,我需要知道的是,有没有办法使用注释(如@EJB、@Inject、@Resource)注入 EJB(或 ManagedBean)
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;
}
}
以下代码不起作用(变量逻辑从未初始化 - null),我在 WEB-INF 目录中有一个空的 beans.xml 文件。当我直接在 ManagedBean、Servlet 或 EJB 中使用 @Inject 时,它可以工作
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;
}
}
有没有办法使这项工作?