How to wrap the entity data and pass to the spring validator

廉价感情. 提交于 2019-12-11 17:23:21

问题


I am trying to wrap the entity data with some other information such as requestor info. Right now, I have the following code,

public class EntityController {

    @Autowired
    private EntityValidator entityValidator;

    ...

    @InitBinder("entity")
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(entityValidator);
    }

}

and my validitor is like

public class EntityValidator implements Validator {

    @Override
    public boolean supports(Class<?> clz) {
        return Entity.class.equals(clz);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ...
    }

}

For the Object parameter passed into the validate method is the Entity class object now. As I said, I want a customized object with this entity class object wrapped in. Is that possible? If yes, how to do that? Please help. Many thanks.


回答1:


If I understand correctly, you want the Entity instance to be a member of another class (a customized object with this entity class object wrapped in). How about something like this:

public interface EntityHolder {
  Entity getEntity();
}

Which you can implement (the customized object) in a number of ways:

public class RequestorInfo implements EntityHolder {
  private final long requestorId;
  public Entity getEntity() { ... }
}

public class CustomObject2 implements EntityHolder {
  public Entity getEntity() { ... }
}

And then use the validator like this:

public class EntityValidator implements Validator {

  @Override
  public boolean supports(Class<?> clz) {
    return EntityHolder.class.isAssignableFrom(clz);
  }

  @Override
  public void validate(Object obj, Errors errors) {
    EntityHolder holder = (EntityHolder) obj;
    // validate the entity obtained by holder.getEntity()  
  }

}

Notice the equals was changed to isAssignableFrom in the supports method. This enables you to pass in a subclass of EntityHolder.



来源:https://stackoverflow.com/questions/49387869/how-to-wrap-the-entity-data-and-pass-to-the-spring-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!