java - 注入(inject)点有如下注解 : - @org. springframework.beans.factory.annotation.Autowired(required=true)

标签 java spring-boot

我是 Spring Boot 新手,在编写文件上传 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 类:
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());
    }
}

服务等级:
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);
        }
    }

配置类:
@ConfigurationProperties(prefix = "file")
public class FileStorageProperties {

    private String uploadDir;

    public String getUploadDir()
    {
        return uploadDir;
    }

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

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

属性文件
## 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

我正在尝试读取文件上传属性并将其传递给 Controller ​​类。

最佳答案

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

正如评论中所说,确保你上课 FileStorageService@Service 注释或 @Component :

@Service
public class FileStorageService {
...
}

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

顺便提一下改进代码的几点注意事项:
  • 当你的类只有一个非默认构造函数时,使用@Autowired在构造函数上是可选的。
  • 不要在构造函数中放置太多代码。改用 @PostConstruct注解。
  • 
        @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);
                }
            }
        }
    
    
  • 最好避免使用 @Autowired在一个领域。请改用构造函数。它更适合您的测试,并且更易于维护:
  • public class FileController {
        private FileStorageService service;
    
        public FileController(FileStorageService service) {
            this.service = service;
        }
    }
    

    关于java - 注入(inject)点有如下注解 : - @org. springframework.beans.factory.annotation.Autowired(required=true),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59993124/

    相关文章:

    java - spring boot + redis cache + @Cacheable 适用于某些方法而不适用于其他方法

    java - Liquibase 不会从 Spring Boot 中的现有数据库在 src/main/resources 文件夹中生成更改日志文件

    java - 规则的 Sonar 名称 [repository=xxx key=yyy] 为空

    java - HttpURLConnection POST 请求不返回任何值

    java - 正在运行引用另一个 jar 的 jar

    java - 如何重写compareTo()。如果它是可能的

    java - 将/注销请求重定向到/api/logout webflux spring boot

    java - 如何规避检查框架 type.invalid 错误?

    java - 如何使用泛型类型模拟 ResponseEntity<?> ?

    java - 使用 rest 客户端将 excel 文件上传到 rest 服务会导致 400 Bad request