我认为这是一个非常基本的问题-
关于此错误有多种问题,但前 5 个结果中没有一个具有 Spring 的细微差别。
我有一个在 Spring 编写的 REST-ful webapp 的开始。我正在尝试将其连接到数据库。
我有一个名为 Workspace 的实体,我正在尝试使用 bean 的 spring 注入(inject)(正确的术语?)来保存工作区实体的实例
package com.parrit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.parrit.models.Workspace;
import com.parrit.models.WorkspaceRepository;
@RestController
@RequestMapping("/workspace")
public class WorkspaceController {
@Autowired
private final WorkspaceRepository repository;
@RequestMapping(method = RequestMethod.POST)
void save( @RequestBody String workspaceHTML) {
Workspace ws = new Workspace();
ws.setHTML(workspaceHTML);
repository.save(ws);
}
}
我的错误在于存储库变量 private final WorkspaceRepository 存储库
。编译器提示它可能没有被初始化并且尝试运行应用程序会产生相同的结果。
如何将此存储库对象的实例放入我的 Controller 中以便对其进行保存操作?
最佳答案
在字段上使用 @Autowired
和 final 是矛盾的。
后者说:这个变量只有一个值,在构造时初始化。
前者说:Spring 将构造对象,将该字段保留为 null(其默认值)。然后 Spring 将使用反射使用 WorkspaceRepository 类型的 bean 初始化该字段。
如果您希望 Autowiring 最终字段,请使用构造函数注入(inject),就像您自己进行注入(inject)一样:
@Autowired
public WorkspaceController(WorkspaceRepository repository) {
this.repository = repository;
}
关于java - Spring io @Autowired : The blank final field may not have been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34580033/