使用Spring @ConfigurationProperties在运行测试JHipster应用程序时给出nullpointer

时间:2016-10-14 14:18:51

标签: spring spring-boot jhipster spring-test

您好我使用Spring Boot 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的新手,我已经坚持了几个小时这个问题,不知道如何修复它。有任何想法吗?

感谢。

1 个答案:

答案 0 :(得分:1)

尝试添加@value注释:

@Value("upload")
private String upload;

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

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