首页 > 解决方案 > 如何从spring的application.properties定义和读取对象数组?

问题描述

在我的 Java 类中,我想读取一个变量,该变量将一次性给我一个标记列表,我的标记是一个具有名称、值和启用字段的对象。

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

如何在我的 application.properties 文件中定义它,以便我可以一次读取所有令牌。例如,我有如下标记:

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

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

我尝试了其他链接,但找不到一次阅读所有内容的方法。

想像这样创建bean

@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())));
    }
}

标签: javaspringspring-boot

解决方案


在具有要从 配置的属性的类上使用@ConfigurationPropertieswith 。prefixapplication.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

学生.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 + "]";
    }
}

令牌.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);
    }

}

证明(输出):

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: 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)

编辑答案:

BeanConfig 类:

@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())));
    }
}

属性配置类:

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

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

推荐阅读