spring 为什么我在自动连接字段上得到空指针异常?[关闭]

67up9zun  于 2023-04-19  发布在  Spring
关注(0)|答案(1)|浏览(138)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包括desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
6天前关闭。
Improve this question
你可能认为我用new创建了一个对象,所以这就是为什么我得到这个错误,但答案是否定的。
下面是我能举的最简单的例子:https://github.com/victorqedu/SOQ001
所以错误是:

java.lang.NullPointerException: Cannot invoke "com.example.demo.Subject.getText()" because "this.subject" is null
    at com.example.demo.SearchBase.runTest(SearchBase.java:16) ~[classes/:na]

并且“subject”成员是@Autowired,并且包含它的类不是用new创建的,在我的所有项目中没有“new”。
我认为问题的根源在于rest控制器中的“@RequestBody SearchTest object)”行,因为不知何故,我认为这里在Spring上下文之外自动创建了一个SearchTest示例。但这并不能帮助我找到解决方案...我需要有一个转换为对象的@RequestBody。

@RestController
@RequestMapping("/api")
public class TestRestController {
    private final TestService service;

    @Autowired
    public TestRestController(TestService theService) {service = theService;}

    @PostMapping("/test")
    public String test(@RequestBody SearchTest object) {
        return service.test(object);
    }
}

为了测试我从POSTMAN访问http://localhost:8080/api/test

**LATER EDIT:**作为POST方法的输入,我提供了以下字符串:[2019 - 04 - 21]

我错误地认为我可以有额外的属性,而不是在输入JSON中,我可以@Autowire他们...我不清楚为什么这是不可能的,但显然,这是问题所在。

**最后编辑:**基本问题是为什么我不能在这种情况下自动连接。

oo7oh9g9

oo7oh9g91#

您的NPE与自动装配无关。异常是由从请求体解析的参数@RequestBody SearchTest object触发的。
尝试使用以下正文发送POST请求:

{
    "subject" : {
        "text": "TEST" 
    }
}

并在IDE中调试接收/解析的object参数。

相关问题