创建 bean 时出错 - 在服务中注入配置类不起作用

我尝试实现一个 REST 服务,如本教程中所示: 教程

但我收到了这个错误:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageService' defined in file: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.airgnb.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException

Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.airgnb.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException

Caused by: java.lang.NullPointerException

服务等级:


@Service

public class FileStorageService {


    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 FileStorageServiceException("Could not create the directory where the uploaded files will be stored.", ex);

        }

    }

}

配置类别:


@Configuration

@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 TestApp implements InitializingBean {

我认为唯一不同的是我使用 application.yml 而不是 application.properties,但我定义的属性与教程类似,但只是采用 yml 样式。


我不知道为什么FileStorageProperties没有注入,因此FileStorageService无法创建。


@Import(FileStoroageProperties.class)我已经尝试使用其他一些依赖注入方式(例如字段注入)来注释应用程序。


Qyouu
浏览 166回答 1
1回答

萧十郎

我认为没有FileStorageProperties被注射。该错误表明未FileStorageProperties找到该类型的 Bean。你只有一个NullPointerException构造函数内部。我想fileStorageProperties.getUploadDir()回来了null。file.uploadDir您是否在 application.yml 或 application.properties 中设置了该属性?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java