创建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)以及其他一些依赖注入方式(如字段注入(对应用程序进行注释。

我不认为FileStorageProperties没有被注入。该错误将表明未找到类型为FileStorageProperties的Bean。您只需要在构造函数中有一个NullPointerException

我认为fileStorageProperties.getUploadDir()返回了null

您是否在application.yml或application.properties中设置了属性file.uploadDir

最新更新