SpringBoot 加载复杂的 yml 文件

**package com.boot.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;


@Configuration
@ConfigurationProperties(prefix = "spring.redis;pool.max;pool.min")
@PropertySource(value = "classpath:redis.yml")
public class RedisConfiguration implements ApplicationListener<ApplicationEvent> {
    @Value("${host}")
    private String host;

    @Value("${port}")
    private Long port;

    @Value("${timeout}")
    private Long timeout;

    @Value("${database}")
    private Long database;

    @Value("${wait}")
    private Long poolMaxWait;

    @Value("${idle}")
    private Long poolMaxIdle;

    @Value("${idle}")
    private Long poolMinIdle;

    @Value("${active}")
    private Long poolMaxActive;


    public void onApplicationEvent(ApplicationEvent event) {
        // 打印属性
        System.out.println("============= redisConnect ================");
        System.out.println(this.toString());
    }


    @Override
    public String toString() {
        return "RedisConfiguration [host=" + host + ", port=" + port + ", timeout=" + timeout
                + ", database=" + database + ", poolMaxWait=" + poolMaxWait + ", poolMaxIdle="
                + poolMaxIdle + ", poolMinIdle=" + poolMinIdle + ", poolMaxActive=" + poolMaxActive
                + "]";
    }


}**
#多层配置

spring:
    redis:
        database: 0
        host: localhost
        port: 6379
        timeout: 0
        pool:
           max:
              active: 8
              wait: -1
              idle: 8
           min:
              idle: 0
日志打印如下所示:
============= redisConnect ================
RedisConfiguration [host=localhost, port=6379, timeout=0, database=0, poolMaxWait=-1, poolMaxIdle=0, poolMinIdle=0, poolMaxActive=8]

参考:

1、spring boot加载复杂的yml文件获取不到值的问题
https://my.oschina.net/u/2486137/blog/1512294


猜你喜欢

转载自blog.csdn.net/HeatDeath/article/details/80286137