简体   繁体   English

如何在Spring中连接文件中的JSON数据?

[英]How to wire a JSON data from file in Spring?

I have a simple Spring App. 我有一个简单的Spring App。 In that app I have @Repository which should provide access to JSON file with my data. 在该应用程序中,我有@Repository ,它应提供对JSON文件及其数据的访问权限。

@Repository("jsonStorageUserRepository")
public class JsonUserRepository implements UserRepository {

    @Value("${users}")
    private List<User> users;

    @Override
    public User getByCursor(Cursor cursor) {
        return users.get(cursor.getId);
    }
}

My users.json file (storage) in properties folder - 我的users.json文件(存储)在properties文件夹中-

[
    {
        "name": "Bill",
        "registered": true
    },
    {
        "name": "John",
        "registered": true
    }
]

And my DTO class - 还有我的DTO课程-

public class User implements Serializable {
    private boolean registered;
    private String name;

    public User(String name, boolean redistricted) {
        this.name = name;
        registered = redistricted;
    }
    // setters and getters were omitted
}

Right now I have exception: 现在我有例外:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jsonStorageUserRepository': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.util.List com.springapp.mvc.repository.json.JsonUserRepository.users; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'users' in string value "${users}"

It related to this line - 与这条线有关-

@Value("${users}")
private List<User> users;

Is it possible to wire converted List of entities from JSON ? 是否可以从JSON转换后的实体列表?

It will not work reading JSON-format-properties file. 读取JSON-format-properties文件将不起作用。 You need write your custom property editor. 您需要编写自定义属性编辑器。 Have a look at that article: 看看那篇文章:

http://christopherhunt-software.blogspot.de/2010/04/spring-propertyeditor-for-json-map-and.html http://christopherhunt-software.blogspot.de/2010/04/spring-propertyeditor-for-json-map-and.html

spring doesn't find your property file: spring找不到您的属性文件:

Could not resolve placeholder 'users' in string value "${users}"

at

@Value("${users}")

Maybe the PropertyPlaceHolderConfigurer is wrong configured. 也许PropertyPlaceHolderConfigurer配置错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM