Java 在服务中创建bean注入配置类时出错
我尝试实现本教程中的REST服务: 但我有一个错误:Java 在服务中创建bean注入配置类时出错,java,spring,spring-boot,dependency-injection,Java,Spring,Spring Boot,Dependency Injection,我尝试实现本教程中的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.bea
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(filestorageproperties.class)
和一些其他依赖注入方式(如字段注入)来注释这个应用程序 我不认为没有注入FileStorageProperties
。该错误表明未找到类型为FileStorageProperties
的Bean。
构造函数中只有一个NullPointerException
我认为fileStorageProperties.getUploadDir()
返回了null
您是否在application.yml或application.properties中设置了属性
file.uploadDir
?我认为没有注入FileStorageProperties
。该错误表明未找到类型为FileStorageProperties
的Bean。
构造函数中只有一个NullPointerException
我认为fileStorageProperties.getUploadDir()
返回了null
您是否在application.yml或application.properties中设置了属性
file.uploadDir
?它是在application.yml中设置的,但不是在test/application.yml中设置的。