Spring @ConfigurationProperties 的使用在 运行 测试时给出空指针,JHipster 应用程序

Usage of Spring @ConfigurationProperties gives nullpointer when running tests, JHipster app

您好,我已经使用 spring 启动 ConfigurationProperties 注释实现了一个简单的文件上传例程,因此我可以从我的 yaml 配置文件加载目录:

服务:

@Service
public class FileSystemStorageService implements StorageService {

private final Logger log = LoggerFactory.getLogger(FileSystemStorageService.class);

private final Path pictureLocation;

@Autowired
public FileSystemStorageService(StorageProperties storageProperties) {
    pictureLocation = Paths.get(storageProperties.getUpload());
}

和 StorageProperties:

@Component
@ConfigurationProperties("nutrilife.meals")
public class StorageProperties {

    private String upload;

    public String getUpload() {
        return upload;
    }

    public void setUpload(String upload) {
        this.upload= upload;
    }
}

在我的 yaml 文件中:

nutrilife:
    meals:
        upload: /$full_path_to_my_upload_dir

这在正常的 spring 启动 运行 时间完美运行,但是当我尝试 运行 我的集成测试时问题开始了,它抛出错误:

java.lang.IllegalStateException: Failed to load ApplicationContext
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileSystemStorageService' defined in file [/home/mmaia/git/nutrilife/build/classes/main/com/getnutrilife/service/upload/FileSystemStorageService.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.getnutrilife.service.upload.FileSystemStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:279)

...
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.getnutrilife.service.upload.FileSystemStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:154)

所以基本上在测试期间,yaml 文件配置看起来好像没有被正确拾取。我是 Spring 的新手,我已经被这个问题困扰了几个小时,不知道如何解决。有任何想法吗?

谢谢。

尝试添加@value 注释:

@Value("upload")
private String upload;

以上答案对 application.properties 配置有效。 它也适用于 yaml。

您可以在此处找到正确的 yaml 配置: 24.6 Using YAML instead of Properties