Home > other >  How to define and read array of objects from spring's application.properties?
How to define and read array of objects from spring's application.properties?

Time:10-21

In my Java class, I want to read a variable that will give me a list of tokens in one shot and my token is an object with fields as name, value, and enabled.

@Value("authorised_applications")
private List<Token> tokenList;

How do I define this in my application.properties file so that I can read all tokens at once. For eg: I will have tokens as

token1
- value: 123456,
- name: specialToken,
- enabled: true

token2
- value: 56173,
- name: newToken,
- enabled: false

I have tried other links but could not find a way to read this all at once.

Edit: Want to create bean like this

@ConfigurationProperties("authorised")
@Configuration
public class AppTokenConfiguration {
    private final List<TokenStore.Token> tokenList = new ArrayList<>();

    @Bean
    public TokenStore getTokenStore() {
        return new TokenStore(tokenList.stream().collect(Collectors.toMap(TokenStore.Token::getToken, Function.identity())));
    }
}

CodePudding user response:

Use @ConfigurationProperties with prefix on the Class which has properties to be configured from application.properties.

application.properties:

my.tokenList[0].name=test1
my.tokenList[0].value=test2
my.tokenList[0].enabled=true

my.tokenList[1].name=test3
my.tokenList[1].value=test4
my.tokenList[1].enabled=false

server.port=8080

Student.java

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@ConfigurationProperties("my")
@Component
public class Student {

    private final List<Token> tokenList = new ArrayList<>();

    public List<Token> getTokenList() {
        return tokenList;
    }

    @Override
    public String toString() {
        return "TestNow [tokenList="   tokenList   "]";
    }
}

Token.java

public class Token {

    private String value;
    private String name;
    private boolean enabled;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    @Override
    public String toString() {
        return "Token [value="   value   ", name="   name   ", enabled="   enabled   "]";
    }

}

ValidateStudent.java

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ValidateStudent {

    @Autowired
    private Student student;

    @PostConstruct
    private void init() {
        System.out.println("printing Student Object---> "   student);
    }

}

Proof(output):

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::       (v2.6.0-SNAPSHOT)

2021-10-20 21:17:30.083  INFO 14632 --- [           main] c.e.S.SpringBootCollectionsApplication   : Starting SpringBootCollectionsApplication using Java 14.0.2 on Machine with PID 14632 (D:\workspaces\Oct20_app_properties\SpringBootCollections\target\classes started by D1 in D:\workspaces\Oct20_app_properties\SpringBootCollections)
2021-10-20 21:17:30.088  INFO 14632 --- [           main] c.e.S.SpringBootCollectionsApplication   : No active profile set, falling back to default profiles: default
2021-10-20 21:17:31.869  INFO 14632 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2021-10-20 21:17:31.891  INFO 14632 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2021-10-20 21:17:31.891  INFO 14632 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.53]
2021-10-20 21:17:32.046  INFO 14632 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2021-10-20 21:17:32.046  INFO 14632 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1869 ms
printing Student Object---> TestNow [tokenList=[Token [value=test2, name=test1, enabled=true], Token [value=test4, name=test3, enabled=false]]]
2021-10-20 21:17:32.654  INFO 14632 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2021-10-20 21:17:32.675  INFO 14632 --- [           main] c.e.S.SpringBootCollectionsApplication   : Started SpringBootCollectionsApplication in 3.345 seconds (JVM running for 3.995)

Edit Answer:

BeanConfig Class:

@Configuration
public class AppConfig {
   
    @Autowired
    private AppTokenConfiguration appTokenConfiguration;

    @Bean
    public TokenStore getTokenStore() {
        return new TokenStore(appTokenConfiguration.getTokenList().stream().collect(Collectors.toMap(TokenStore.Token::getToken, Function.identity())));
    }
}

PropertyConfigClass:

@ConfigurationProperties("authorised")
@Component
public class AppTokenConfiguration {

    private final List<TokenStore.Token> tokenList = new ArrayList<>();
    
    public void getTokenList(){
     return tokenList;
    }
}
  • Related