平台:JBoss AS 7。
我看到了JSR 303 bean验证和请求范围的CDI托管bean的奇怪行为。系统似乎永远不会应用验证规则并始终通过验证。
以下是代码段。
@Named
@RequestScoped
class Person {
@Size(min=3, max=25, message="Please enter a valid name")
private String firstName;
//Getters and setters...
}
@WebServlet("/ValidationTest")
public class ValidationTest extends HttpServlet {
@Inject
Person p1;
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
p1.setFirstName("A");
validate(p1);
Person p2 = new Person();
p2.setFirstName("B");
validate(p2);
}
public void validate(Object o) {
ValidatorFactory validatorFactory = null;
validatorFactory = Validation.buildDefaultValidatorFactory();
ValidatorContext validatorContext = validatorFactory.usingContext();
javax.validation.Validator beanValidator = validatorContext
.getValidator();
Set<ConstraintViolation<Object>> violations = beanValidator.validate(o);
System.out.println("Object is valid: " + violations.isEmpty());
}
}
这个输出是:
Object is valid: true
Object is valid: false
注入的bean p1被认为是有效的,这不应该发生。 p2的验证失败,这是预期的。如果我使Person bean依赖于作用域,那么p1被正确地视为无效。我做错了什么?
编辑:我在TomEE中重复了这一行为。所以,我一定是做错了。