简体   繁体   中英

Spring @RequestBody and default values

Spring creates a new Object of the correct type when receiving the details as an @ResponseBody parameter (eg public void createUser(@RequestBody User user) . I'm sending the data to the server as JSON, and Spring creates the new user object as specified.

My question is, is there anyway to get Spring to ignore the auto-generated fields I have (like createDate, etc). So, if I, for example, pass in {"username":"sam"} and nothing else, I'd like a user object that only has the username field populated, and none of the other fields (even if that is invalid).

The reason I am asking this is because my User inherits some default autogenerated attributes from another object which I cannot touch, and I need to have an object that has all fields null except for the fields that come in from the request. update: I can then merge the newly created object with the object in the JpaRepository (ignoring the nulls).

Thank you :-)

If you return a User object, all fields are included automaticly by default, you cann't change it. but you can just return a HashMap with uername populated.

@ResponseBody public Map createUser(@RequestBody User user) {
    ...
    Map userCreated = new HashMap();
    userCreated.put("username", user.getUsername());
    return userCreated;
}

In other way, you can define and create a new UserForm object to do what you expect to return as below.

public class UserForm{

    private String username;

    public UserForm(User user){
        this.username = user.getUsername();
    }

    public void setUsername(String username){
        this.username = username;
    }

    public String getUsername(){
        return this.username;    
    }
}

@ResponseBody public UserForm createUser(@RequestBody User user) {
    ...

    return new UserForm( user );
} 

Hope it will help.

It do have the way to do that. For example: @initBinder or convertService , but it will be more complex, and I also don't know exact implementation to do that code. While the easiest way is that you create a new class, may be called: TmpUser and just has 1 field: userName, you use this class to accept the request data, and copy the data to User, then it can meet you requirement. You can use Spring utils. BeanUtils.copyProperties() Spring utils. BeanUtils.copyProperties() to do the copy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM