Spring中org.json.JSONObject依赖注入失败问题咨询
错误原因分析
@Autowired JSONObject json报错核心:org.json.JSONObject是普通Java工具类,没有被Spring的@Component/@Service等注解标记为可管理Bean,Spring容器中不存在该类型的实例,因此@Autowired无法找到可注入的对象。@Autowired Question question的隐患:Question是实体类,不属于Spring管理的Bean范畴,注入它不仅会触发类似的找不到Bean错误,还会导致多请求复用同一个实例,引发线程安全问题。- 业务逻辑错误:
addQuestion方法中注释掉了json = new JSONObject(newQuestionObj);,即使注入成功也会触发空指针异常;同时请求体字段(如title)和代码中获取的newQuestion不匹配,会导致字段取值失败。
解决方案
1. 移除错误的依赖注入
直接删除以下两行无效注入代码:
@Autowired private JSONObject json; @Autowired private Question question;
2. 修正addQuestion方法逻辑
在需要使用JSONObject和Question的地方直接创建实例,同时匹配请求体字段:
@PostMapping("/addquestion") public String addQuestion(@RequestBody String newQuestionObj) { System.out.println(newQuestionObj); // 直接创建JSONObject实例解析请求体 JSONObject json = new JSONObject(newQuestionObj); // 创建新的Question实例,避免多请求复用 Question question = new Question(); // 注意:此处需匹配你的Question实体类字段,若实体类字段是title则用setTitle,根据实际调整 question.setTitle(json.getString("title")); question.setOptA(json.getString("optA")); question.setOptB(json.getString("optB")); question.setOptC(json.getString("optC")); question.setAnswer(json.getString("answer")); questionRepository.save(question); // 构建返回结果 JSONObject responseJson = new JSONObject(); responseJson.put("success", "Question Inserted Successfully"); return responseJson.toString(); }
3. 可选优化:使用Spring自动绑定请求体
无需手动解析JSON,让Spring直接将请求体映射到Question对象,代码更简洁:
@PostMapping("/addquestion") public String addQuestion(@RequestBody Question newQuestion) { questionRepository.save(newQuestion); JSONObject responseJson = new JSONObject(); responseJson.put("success", "Question Inserted Successfully"); return responseJson.toString(); }
注意:此方式要求
Question实体类有对应的getter/setter方法,且请求体字段名和实体类属性名一致。
4. 确保依赖完整性
如果项目未引入org.json依赖,需在构建文件中添加:
Maven(pom.xml)
<dependency> <groupId>org.json</groupId> <artifactId>json</artifactId> <version>20240303</version> <!-- 可替换为最新版本 --> </dependency>
Gradle(build.gradle)
implementation 'org.json:json:20240303'
内容的提问来源于stack exchange,提问作者19001011057 SHRAVAN KHAR
相关产品推荐
相关产品推荐

