Spring io @Autowired:空白的最终字段可能尚未初始化 [英] Spring io @Autowired: The blank final field may not have been initialized
问题描述
我认为这是一个非常基本的问题 -
what I assume is a pretty basic question here-
关于这个错误有几种问题,但前5个结果中没有一个有额外的细微差别Spring。
There are several flavors of questions regarding this error, but none in the first 5 results that have the added nuance of Spring.
我有一个在春天写的REST-ful webapp的开头。我正在尝试将它连接到数据库。
I have the beginnings of a REST-ful webapp written in spring. I am trying to connect it to a database.
我有一个名为Workspace的实体,我正在尝试使用bean的弹簧注入(正确的术语?)来保存工作区实体的实例
I have an entity named Workspace and am trying to use the spring injection of a bean( correct terminology ?) to save an instance of the workspace entity
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);
}
}
我的错误在于存储库变量私有最终WorkspaceRepository存储库
。编译器抱怨它可能没有初始化并且尝试运行应用程序会产生相同的结果。
My error is on the repository variable private final WorkspaceRepository repository
. The compiler is complaining that it may not be initialized and attempting to run the app yields the same result.
如何将此存储库对象的实例添加到我的控制器中为了对它进行保存操作?
How do I get an instance of this repository object into my controller in order to do save operations on it?
推荐答案
拥有 @Autowired
和场上的决赛是矛盾的。
Having @Autowired
and final on a field are contradictory.
后者说:这个变量有一个且只有一个值,它在施工时被初始化。
The latter says: this variable has one and only one value, and it's initialized at construction time.
前者说:Spring将构造对象,将此字段保留为null(默认值)。然后Spring将使用反射来使用类型为WorkspaceRepository的bean初始化此字段。
The former says: Spring will construct the object, leaving this field as null (its default value). Then Spring will use reflection to initialize this field with a bean of type WorkspaceRepository.
如果您想要自动连接最终字段,请使用构造函数注入,就像您执行操作一样自己注入:
If you want final fields autowired, use constructor injection, just like you would do if you did the injection by yourself:
@Autowired
public WorkspaceController(WorkspaceRepository repository) {
this.repository = repository;
}
这篇关于Spring io @Autowired:空白的最终字段可能尚未初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!