Search code examples
javajsonspringspring-bootapplication.properties

Is there any way to write JSON array list in application.properties file (spring-boot)


Is there any way to write Json array list in application.properties file (spring-boot), so that I can read whole Json with minimum code?

Below is my json object.

{ "userdetail": [
    {
      "user": "user1",
      "password": "password2",
      "email": "email1"
    },
    {
      "user": "user2",
      "password": "password2",
      "email": "email2"
    }]}

And also if I use jasypt to encode password, then what the code will be?


Solution

  • Refer to Spring Boot Docs here

    You can use YAML

    my:
       servers:
           - dev.example.com
           - another.example.com
    

    or normal configuration property arrays:

    my.servers[0]=dev.example.com
    my.servers[1]=another.example.com
    

    Than you can load these properties into application this way:

    @ConfigurationProperties(prefix="my")
    public class Config {
    
        private List<String> servers = new ArrayList<String>();
    
        public List<String> getServers() {
            return this.servers;
        }
    }
    

    For your case I would try something like:

    users.userdetail[0].user=..
    users.userdetail[0].password=..
    ...
    

    And read it via

    @ConfigurationProperties(prefix="users")
    public class Userdetail {
    
        private class User {
             public String user;
             public String password;
             public String email;
        }  
    
        private List<User> userdetails = new ArrayList<User>();
    
        public List<User> getUserdetails() {
            return this.userdetails;
        }
    }