问题
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