Spring Boot 配置(六)配置 Map

2,332 阅读1分钟

Spring Boot 获取配置数据时,可以定义特定类,也可以使用Map数据结构。

以下面配置为例:

student:
  scores:
    math: 100
    physics: 90
    sports: 95

一、定义特定类

package com.example.demo;

import javax.annotation.PostConstruct;

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

@Component
@ConfigurationProperties(prefix = "student.scores")
public class StudentScore {

    private Integer math;

    private Integer physics;

    private Integer sports;

    // Getter Setter 注意代码中要有,这里为了节省篇幅省略

    @PostConstruct
    public void postConstruct() {
        System.out.println("math score: " + math);
        System.out.println("physics score: " + physics);
        System.out.println("sports score: " + sports);
    }
}

二、使用Map数据结构

package com.example.demo;

import java.util.Map;

import javax.annotation.PostConstruct;

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

@Component
@ConfigurationProperties(prefix = "student")
public class StudentScore {

    private Map<String, Integer> scores;

    public Map<String, Integer> getScores() {
        return this.scores;
    }

    public void setScores(Map<String, Integer> scores) {
        this.scores = scores;
    }

    @PostConstruct
    public void postConstruct() {
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + "=" + entry.getValue());
        }
    }
}

注意ConfigurationProperties注解中prefix的值。