【发布时间】:2018-02-14 11:21:50
【问题描述】:
我使用 Jhipster 生成了我的 Spring 应用程序。现在我想为 FilesUpload 添加控制器,并为其添加 StorageService。但是当我运行我的应用程序时,它会收到这条消息
说明:com.kongresspring.myapp.web.rest.FileUploadResource 中构造函数的参数 0 需要一个无法找到的 'com.kongresspring.myapp.service.StorageService' 类型的 bean。 行动:考虑在你的配置中定义一个“com.kongresspring.myapp.service.StorageService”类型的bean。
我找不到 beans.xml 来添加新的 bean。我是春天的新手,所以也许还有其他配置bean的方法,我不熟悉。这是我上传文件控制器的代码:
package com.kongresspring.myapp.web.rest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.kongresspring.myapp.service.StorageService;
@RestController
@RequestMapping("/api")
public class FileUploadResource {
private final Logger log = LoggerFactory.getLogger(FileUploadResource.class);
private final StorageService storageService;
@Autowired
public FileUploadResource(StorageService storageService) {
this.storageService = storageService;
}
/**
* POST uploadFile
*/
@PostMapping("/upload-file")
public String uploadFile(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
storageService.store(file);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded " + file.getOriginalFilename() + "!");
return "success";
}
/**
* GET preview
*/
@GetMapping("/preview")
public String preview() {
return "preview";
}
}
这是我的 StorageService 代码:
package com.kongresspring.myapp.service;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;
import java.nio.file.Path;
import java.util.stream.Stream;
public interface StorageService {
void init();
void store(MultipartFile file);
Stream<Path> loadAll();
Path load(String filename);
Resource loadAsResource(String filename);
}
【问题讨论】: