application.yml 使用数组

  1. application.yml 里的配置
server:
  port: 9001
app:
  id: speech
knowledge:
  init:
    knowledgeTitles:
      - kdTitle: 听不清
        keyWords: "[你说什么,没听清,听不清楚,再说一遍]"
        question: "[没听懂,听不清楚]"
      - kdTitle: 无应答
        kdInfos:
          - 你好
          - hello
          - hi

(用 - 来表示数组)

  1. 初始化类
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * @author jly
 * @describe 从application.yml中读取初始值
 */
@Component
@ConfigurationProperties(prefix="knowledge.init")
@Slf4j
public class SpeechInfoConfig {
	// 名称要和application.yml 里配置的一样,必须有get和set方法
  private List knowledgeTitles = new ArrayList<>();

  public static class KnowledgeTitle{

    private String kdTitle;
    private String keyWords;
    private String question;
    private String[] kdInfos;

    public String getKdTitle() {
      return kdTitle;
    }

    public void setKdTitle(String kdTitle) {
      this.kdTitle = kdTitle;
    }

    public String getKeyWords() {
      return keyWords;
    }

    public void setKeyWords(String keyWords) {
      this.keyWords = keyWords;
    }

    public String getQuestion() {
      return question;
    }

    public void setQuestion(String question) {
      this.question = question;
    }

    public String[] getKdInfos() {
      return kdInfos;
    }

    public void setKdInfos(String[] kdInfos) {
      this.kdInfos = kdInfos;
    }

    @Override
    public String toString() {
      return "KnowledgeTitle{" +
          "kdTitle='" + kdTitle + '\'' +
          ", keyWords='" + keyWords + '\'' +
          ", question='" + question + '\'' +
          ", kdInfos=" + Arrays.toString(kdInfos) +
          '}';
    }
  }

  public List getKnowledgeTitles() {
    return knowledgeTitles;
  }

  public void setKnowledgeTitles(
      List knowledgeTitles) {
    this.knowledgeTitles = knowledgeTitles;
  }


/**
   * Spring Boot中初始化资源的方式之一  @PostConstruct
   */
  @PostConstruct
  public void initSpeech(){

    if(!ObjectUtils.isEmpty(knowledgeTitles)){
      for(KnowledgeTitle knowledgeTitle : knowledgeTitles){
        log.info("knowledgeTitle is :{}",knowledgeTitle );
      }
    }

  }
}
  1. 设置启动类
@SpringBootApplication
public class TestYmlApplication {

  public static void main(String[] args) {
    SpringApplication.run(TestYmlApplication.class, args);
  }

}
  1. 若SpringInfoConfig类提示飘红
    application.yml 使用数组_第1张图片
    在pom.xml中添加下面的jar包,即可解决:

      org.springframework.boot
      spring-boot-configuration-processor
      true
    
  1. 运行,查看log
    在这里插入图片描述
  2. 若中文显示为乱码,在setting 里修改下文件编码格式
    application.yml 使用数组_第2张图片

你可能感兴趣的:(java)