java - 如何使用 JSR 注释组从 bean 获取属性?

标签 java spring spring-mvc bean-validation jsr

我有一个表单 bean(Employee),可以在不同的屏幕上共享。为了区分不同屏幕上的字段,我计划使用带有组名称的 JSR 自定义注释对字段进行分组。

例如,

class Employee {

@Screen(groups={EmployeeScreen.class})
private employeeNo;

@Screen(groups={EmployeeScreen.class})
private employeeName;

@Screen(groups={RoleScreen.class})
private roleName;

我如何读取与组名称(EmployeeScreen 和 RoleScreen)关联的 bean 的所有属性名称。任何帮助将非常感激。谢谢。

最佳答案

Bean Validation 提供元数据 API,因此只要您有权访问 Validator 实例,您就可以执行以下操作:

BeanDescriptor beanDescriptor = validator.getConstraintsForClass( Employee.class );

Set<PropertyDescriptor> propertyDescriptors = beanDescriptor.getConstrainedProperties();

for(PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    Set<ConstraintDescriptor<?>> descriptorsForGroup = propertyDescriptor.findConstraints()
                .unorderedAndMatchingGroups( EmployeeScreen.class )
                .getConstraintDescriptors();

     // if descriptorsForGroup is not empty you found a property which has a constraint matching the specified group
     // propertyDescriptor.getPropertyName() gets you the property name

}

这是否对您有帮助取决于上下文。您是否使用 Bean Validation 作为其他框架的一部分?

关于java - 如何使用 JSR 注释组从 bean 获取属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33088328/

相关文章:

java - 在多线程程序线程中执行一个类的静态方法是否安全?

java - `new Class<?>[] {}` 是什么意思?

java - 静态 block 未在 JDK 7 中执行, "Main method not found",但在 JDK 1.5 中有效

java - Spring - @Transactional - 在后台发生了什么?

maven - 创建名称为 'mvcContentNegotiationManager'的bean时出错

java - 无法在多文档事务中创建命名空间(MongoDB 4.0、Spring Data 2.1.0、Spring Boot)

java - Flyway 和 JPA 集成

java - 任何以注释方式在没有Spring的情况下读取属性文件的API

java - Spring MVC Google Search Console 验证

java - 如何在spring中编写/检查auth的权限