spring boot 为什么以静态方法返回为空?
pom.xml
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.0.6</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>locale.demo</groupId>
<artifactId>demo02</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo02</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>20</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
// controller.javapackage locale.demo.demo02.controller;
import locale.demo.demo02.CommonResult;
import locale.demo.demo02.UserVO;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/get2")
public CommonResult<UserVO> get2(@RequestParam("id") Integer id) {
UserVO user = new UserVO().setId(id).setUsername(UUID.randomUUID().toString());
// 返回结果
return CommonResult.success(user);
}
}
// CommonResult.javapackage locale.demo.demo02;
import com.fasterxml.jackson.annotation.JsonIgnore;
import org.springframework.util.Assert;
import java.io.Serializable;
public class CommonResult<T> implements Serializable {
public static Integer CODE_SUCCESS = 0;
private Integer code;
private String message;
private T data;
public Integer getCode() {
return code;
}
public String getMessage() {
return message;
}
public static <K> CommonResult<K> success(K input_data) {
CommonResult<K> result = new CommonResult<>();
result.code = CODE_SUCCESS;
result.data = input_data;
result.message = "";
return result;
}
}
按以上方法写,则只能得到{"code":0,"message":""}
这样的结果;只有将commonresult里的data从private改为public才能返回{"code":0,"message":"","data":{"id":3,"username":"1e29a45d-6363-43b3-a08d-3989ea70d1ae"}}
这样的结果
请问这是为什么?
回答:
你要在 CommonResult 类里写一个公共的 getData 方法就好了:
public T getData() { return data;
}
回答:
因为Controller在返回的时候,需要将返回对象json化,你的data是privite的,也没有get方法,所以json的时候会忽略他
以上是 spring boot 为什么以静态方法返回为空? 的全部内容, 来源链接: utcz.com/p/945165.html