[英]Error creating bean - Inject Configuration-Class in Service does not work
我尝试在本教程中实现 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
?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.