注入点有以下注释: - @org.springframework.beans.factory.annotation.Autowired(required=true)

Aka*_*sh 9 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.*
Run Code Online (Sandbox Code Playgroud)

控制器类:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

服务等级:

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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

配置类:

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

    private String uploadDir;

    public String getUploadDir()
    {
        return uploadDir;
    }

    public void setUploadDir(String uploadDir) {
        this.uploadDir = uploadDir;
    }
}
Run Code Online (Sandbox Code Playgroud)

主要的:

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

属性文件

## 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
Run Code Online (Sandbox Code Playgroud)

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

小智 10

我使用 @Autowired 注释解决了这个问题,只需替换为这个`

@Autowired(required = false)

`

  • 这并不总是解决方案,那么你的 Bean 没有实例化 -&gt; `NullPointerException` (2认同)

RUA*_*ult 9

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

正如评论中所说,请确保您的课程FileStorageService@Serviceor注释@Component

@Service
public class FileStorageService {
...
}
Run Code Online (Sandbox Code Playgroud)

还要确保此类位于您的 class 的子包中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);
            }
        }
    }

Run Code Online (Sandbox Code Playgroud)
  • 最好避免@Autowired在场上。改用构造函数。它更适合您的测试,并且更易于维护:
public class FileController {
    private FileStorageService service;

    public FileController(FileStorageService service) {
        this.service = service;
    }
}
Run Code Online (Sandbox Code Playgroud)