javax.validator with spring component

删除回忆录丶 提交于 2019-12-02 09:54:16

I also tried to solve this, however the tests are fully low level unit tests on my side and I wanted to avoid too much of a context. I couldn't even use your approach. The solution my side was to add a custom ConstraintValidatorBean into the mockmvc. That custom implementation could get a list of validator class Class objects and so if the factory tried to create a validator, I returned a Mockito.mock version of it instead of the real one and I could also look that up for expectation settings.

Feel free to share your knowledge. This is how I solved this task.

I created a Spring component and it has a static field (GroupService which is initialized in constructor).

@Component // Spring component.
class ServiceHolderComponent {

    private static GroupService GROUP_SERVICE;

    @Autowired4
    public ServiceHolderComponent(final GroupService groupService) {
        GROUP_SERVICE = Validate.notNull(groupService); //apache lib
    }

    public static GroupService getGroupService() {
        return GROUP_SERVICE;
    }
}

And now validator with default constructor.

public class EntityDynamicValidator implements ConstraintValidator<SomeConstraint, Entity> {

    private GroupService groupService;

    public UserDynamicEnumValidator() {
        this(ServiceHolderComponent.getGroupService());
    }

    public UserDynamicEnumValidator(final GroupService groupService) {
        this.groupService = groupService;
    }

    @Override
    public boolean isValid(final Entity entity, final ConstraintValidatorContext context) {
        Something something = groupService.findByValue(entity.getValue());
        // Validate all this stuff
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!