当前位置: 首页 > 知识库问答 >
问题:

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

姚新霁
2023-03-14
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.*
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

我正在尝试读取file upload属性并将其传递给controller类。

共有1个答案

史智志
2023-03-14

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

如注释中所述,确保您的类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;
        }
    }
    

  •  类似资料:
    • 我有一个pb,我找不到解决方案,因为我认为我的项目中有多个pb相关: 有人能帮我吗?我可以给你链接到git存储库,也可以看到所有的项目。谢谢。

    • 问题: count属性是必需的&前缀是必需的。如果您看到beanClass2,我将通过构造函数设置属性,在beanClass3中也是如此 但是当我执行代码时,它抛出异常。让我困惑的重要事情是: 2014年12月9日8:47:33 PM org.springframework.beans.factory.support.defaultsingletonbeanregistry destroySing

    • 我正在使用Spring AOP进行日志记录。我想创建一个切入点,该切入点适用于除具有特定注释的方法外的所有方法,但我不知道如何进行。我所发现的只是如何包含带有注释的方法。

    • 我试图在方法注释上创建一个Aeyj切入点,但我总是用不同的方法失败。我使用的是aspectj自动代理(我在Spring上下文中没有配置其他编织)。我的类如下所示: 所以我想知道为什么aspectj不会创建切入点。我设法使用执行(**(…)使其工作抛出一些exc)这对我来说很好,但我仍然想知道我做错了什么。 另外,由于是在接口中定义的,我指定了实现类的注释,有没有办法让它以这种方式工作?其他代理机制

    • @Required注解应用于bean属性的setter方法,它表明影响的bean属性在配置时必须放在XML配置文件中。 十九、请举例说明@Qualifier 注解? 如果在xml中定义了一种类型的多个bean,同时在java注解中又想把其中一个bean对象作为属性,那么此时可以使用@Qualifier加@Autowired来达到这一目的,若不加@Qualifier这个注解,在运行时会出现“ No

    • 和和注释之间有什么区别? 我们应该在什么时候使用它们每一个?