注入点有以下注释: - @org.springframework.beans.factory.annotation.Autowired(required=true) [英] The injection point has the following annotations: - @org.springframework.beans.factory.annotation.Autowired(required=true)

查看:24
本文介绍了注入点有以下注释: - @org.springframework.beans.factory.annotation.Autowired(required=true)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Spring Boot 的新手,在编写文件上传 API 时出现以下错误:

错误:描述:com.primesolutions.fileupload.controller.FileController 中的字段 fileStorageService 需要一个无法找到的类型为com.primesolutions.fileupload.service.FileStorageService"的 bean.注入点有以下注释:- @org.springframework.beans.factory.annotation.Autowired(required=true)行动:考虑在您的配置中定义一个com.primesolutions.fileupload.service.FileStorageService"类型的 bean.*

控制器类:

公共类 FileController{私有静态最终记录器记录器 = LoggerFactory.getLogger(FileController.class);@自动连线私有文件存储服务文件存储服务;@PostMapping("/上传文件")public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {String fileName = fileStorageService.storeFile(file);String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/downloadFile/").path(文件名).toUriString();返回新的 UploadFileResponse(fileName, fileDownloadUri,file.getContentType(), file.getSize());}@PostMapping("/uploadMultipleFiles")公共列表uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {返回 Arrays.asList(files).stream().map(文件 -> 上传文件(文件)).collect(Collectors.toList());}}

服务类:

private final Path fileStorageLocation;@自动连线公共文件存储服务(文件存储属性文件存储属性){this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();试试{Files.createDirectories(this.fileStorageLocation);} 捕捉(异常前){throw new FileStorageException("无法创建存储上传文件的目录.", ex);}}公共字符串存储文件(多部分文件文件){//规范化文件名String fileName = StringUtils.cleanPath(file.getOriginalFilename());试试{//检查文件名是否包含无效字符if(fileName.contains("..")) {throw new FileStorageException("抱歉!文件名包含无效的路径序列" + fileName);}//将文件复制到目标位置(替换现有的同名文件)路径 targetLocation = this.fileStorageLocation.resolve(fileName);Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);返回文件名;} catch (IOException ex) {throw new FileStorageException("无法存储文件" + fileName + ".请再试一次!", ex);}}

配置类:

@ConfigurationProperties(prefix = "file")公共类 FileStorageProperties {私人字符串上传目录;公共字符串 getUploadDir(){返回上传目录;}public void setUploadDir(String uploadDir) {this.uploadDir = 上传目录;}}

主要内容:

@SpringBootApplication@EnableConfigurationProperties({FileStorageProperties.class})公共类文件应用{公共静态无效主(字符串 [] args){SpringApplication.run(FileApplication.class, args);}}

属性文件

## MULTIPART (MultipartProperties)# 启用分段上传spring.servlet.multipart.enabled=true# 文件写入磁盘的阈值.spring.servlet.multipart.file-size-threshold=2KB# 最大文件大小.spring.servlet.multipart.max-file-size=200MB# 最大请求大小spring.servlet.multipart.max-request-size=215MB## 文件存储属性# 所有通过REST API上传的文件都会存放在这个目录中file.upload-dir=C:/Projects/SpringBootProject/Primesolutions/PrimeSolutions/FileUpload

我正在尝试读取文件上传属性并将其传递给控制器​​类.

解决方案

该错误似乎表明 Spring 不知道任何 com.primesolutions.fileupload.service.FileStorageService 类型的 bean.

如评论中所述,确保您的类 FileStorageService@Service@Component 注释:

@Service公共类 FileStorageService {...}

还要确保该类位于您的类 FileApplication 的子包中.例如,如果您的 FileApplication 类位于包 com.my.package 中,请确保您的 FileStorageService 位于包 com 中.my.package.**(相同的包或任何子包).

顺便提一下改进代码的一些注意事项:

  • 当您的类只有一个非默认构造函数时,在构造函数上使用 @Autowired 是可选的.

  • 不要在构造函数中放入太多代码.改用 @PostConstruct 注释.

<预><代码>@服务公共类 FileStorageService {私有 FileStorageProperties 道具;//@Autowired 在这种情况下是可选的公共文件存储服务(文件存储属性文件存储属性){this.props = fileStorageProperties;this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir()).toAbsolutePath().normalize();}@PostConstruct公共无效初始化(){试试{Files.createDirectories(this.fileStorageLocation);} 捕捉(异常前){throw new FileStorageException("无法创建存储上传文件的目录.", ex);}}}

  • 最好避免在字段上使用 @Autowired.改用构造函数.它更适合您的测试,并且更易于维护:

public class FileController {私有文件存储服务服务;公共文件控制器(文件存储服务服务){this.service = 服务;}}

I am new to Spring Boot and I'm getting the following error when writing a file upload API:

Error:Description:
Field fileStorageService in com.primesolutions.fileupload.controller.FileController required a bean of type 'com.primesolutions.fileupload.service.FileStorageService' that could not be found.
The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'com.primesolutions.fileupload.service.FileStorageService' in your configuration.*

Controller class:

public class FileController 
{
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/uploadFile")
    public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file) {
        String fileName = fileStorageService.storeFile(file);

        String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
                .path("/downloadFile/")
                .path(fileName)
                .toUriString();

        return new UploadFileResponse(fileName, fileDownloadUri,
                file.getContentType(), file.getSize());
    }

    @PostMapping("/uploadMultipleFiles")
    public List<UploadFileResponse> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files) {
        return Arrays.asList(files)
                .stream()
                .map(file -> uploadFile(file))
                .collect(Collectors.toList());
    }
}

Service class:

private final Path fileStorageLocation;


    @Autowired
    public FileStorageService(FileStorageProperties fileStorageProperties) {
        this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
                .toAbsolutePath().normalize();

        try {
            Files.createDirectories(this.fileStorageLocation);
        } catch (Exception ex) {
            throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }

    public String storeFile(MultipartFile file) {
        // Normalize file name
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        try {
            // Check if the file's name contains invalid characters
            if(fileName.contains("..")) {
                throw new FileStorageException("Sorry! Filename contains invalid path sequence " + fileName);
            }

            // Copy file to the target location (Replacing existing file with the same name)
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);

            return fileName;
        } catch (IOException ex) {
            throw new FileStorageException("Could not store file " + fileName + ". Please try again!", ex);
        }
    }

Configuration class:

@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {

    private String uploadDir;

    public String getUploadDir()
    {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }
}

Main:

@SpringBootApplication
@EnableConfigurationProperties({
        FileStorageProperties.class
})
public class FileApplication {
    public static void main(String[] args) {
        SpringApplication.run(FileApplication.class, args);
    }
}

properties file

## MULTIPART (MultipartProperties)
# Enable multipart uploads
spring.servlet.multipart.enabled=true
# Threshold after which files are written to disk.
spring.servlet.multipart.file-size-threshold=2KB
# Max file size.
spring.servlet.multipart.max-file-size=200MB
# Max Request Size
spring.servlet.multipart.max-request-size=215MB

## File Storage Properties
# All files uploaded through the REST API will be stored in this directory
file.upload-dir=C:/Projects/SpringBootProject/Primesolutions/PrimeSolutions/FileUpload

I'm trying to read the file upload property and pass it to the controller class.

解决方案

The error seems to indicate that Spring does not know any bean of type com.primesolutions.fileupload.service.FileStorageService.

As said in the comment, make sure you class FileStorageServiceis annotated by @Service or @Component:

@Service
public class FileStorageService {
...
}

Make also sure that this class is located in a sub-package of your class FileApplication. For example, if your FileApplication class is located in a package com.my.package, make sure your FileStorageService is located in the package com.my.package.** (same package or any sub package).

Few notes to improve your code by the way :

  • When your class has only one not default constructor, the use of @Autowired on the constructor is optional.

  • Do not put too much code in your constructor. Use instead the @PostConstruct annotation.


    @Service
    public class FileStorageService {
        private FileStorageProperties props;
        // @Autowired is optional in this case
        public FileStorageService (FileStorageProperties fileStorageProperties) {
            this.props = fileStorageProperties;
            this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
                    .toAbsolutePath().normalize();
        }

        @PostConstruct
        public void init() {
            try {
                Files.createDirectories(this.fileStorageLocation);
            } catch (Exception ex) {
                throw new FileStorageException("Could not create the directory where the uploaded files will be stored.", ex);
            }
        }
    }

  • It is better to avoid the @Autowired on a field. Use the constructor instead. It is better for your tests, and more maintainable:

public class FileController {
    private FileStorageService service;

    public FileController(FileStorageService service) {
        this.service = service;
    }
}

这篇关于注入点有以下注释: - @org.springframework.beans.factory.annotation.Autowired(required=true)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆