我尝试像本教程中那样实现REST服务:Tutorial
但是我遇到了这个错误:
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
。