簡體   English   中英

Spring io @Autowired:空白的最終字段可能尚未初始化

[英]Spring io @Autowired: The blank final field may not have been initialized

我認為這是一個非常基本的問題 -

關於這個錯誤有幾種問題,但前5個結果中沒有一個會增加Spring的細微差別。

我有一個在春天寫的REST-ful webapp的開頭。 我正在嘗試將其連接到數據庫。

我有一個名為Workspace的實體,我正在嘗試使用bean的彈簧注入(正確的術語?)來保存工作區實體的實例

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 repository 編譯器抱怨它可能沒有被初始化並且嘗試運行應用程序會產生相同的結果。

如何將此存儲庫對象的實例添加到控制器中以對其執行保存操作?

@Autowired和最終在一個領域是矛盾的。

后者說:這個變量有一個且​​只有一個值,它在構造時初始化。

前者說:Spring將構造對象,將此字段保留為null(其默認值)。 然后Spring將使用反射來使用WorkspaceRepository類型的bean初始化該字段。

如果您想要自動連接最終字段,請使用構造函數注入,就像您自己進行注入一樣:

@Autowired
public WorkspaceController(WorkspaceRepository repository) {
    this.repository = repository;
}

確切地說,您必須提供一個指定最終字段的構造函數

private final WorkspaceRepository repository;

@Autowired
public WorkspaceController(WorkspaceRepository repository){
  this.repository = repository;
}

Spring將能夠弄清楚如何初始化對象並通過構造函數注入存儲庫

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM