SpringBoot系列14-加载yml,properties配置文件信息

2023-05-16

SpringBoot系列14-加载yml,properties配置文件信息

      • 原文链接:[https://www.lskyf.com/post/73](https://www.lskyf.com/post/73)
      • yml前置知识
        • yml语法:
        • 对象写法
        • list集合写法
        • map集合写法
      • 示例代码
        • 1.pom导入配置文件提示spring-boot-configuration-processor
        • 2.读取application.yml配置
          • application.yml配置文件
          • Student.java实体类代码
          • 测试调用
        • 3.读取application.properties配置
          • application.properties文件
          • StudentProperties.java实体类代码
          • 测试调用
        • 4.读取外部properties文件
          • resource目录下新增stu-external.properties文件
          • ExternalStuProperties.java实体类代码
          • 测试调用
        • 5.读取外部yml文件
          • resource目录下新增application-external.yml文件
          • ExternalStuYml.java实体类代码
          • 测试调用
          • 加载外部yml时需要配置spring.profiles.include=external加入容器,或者bean中配置需要加载的yml文件(springboot新版本此配置已失效参见下面最新加载外部yaml文件)
      • 最新加载外部yaml文件
        • 1.定义MyEnvironmentPostProcessor.java
        • 2.resources/META-INF 文件夹下创建spring.factories文件配置好MyEnvironmentPostProcessor
      • 最后不管对你有没有用,猿份哥还是为你准备了一份完整的代码,万一您想去看看呢!哈哈哈

原文链接:https://www.lskyf.com/post/73

yml前置知识

yml语法:

单个key value 写法
k:空格v
eg: color: blue

对象写法

k: {k1: v1,k2: v2}

k: 
  k1: v1
  k2: v2

list集合写法

k: [v1,v2,v3]
k:
  -v1 
  -v2
  -v3

map集合写法

k:{k1: v1,k2: v2}  
k: 
  k1: v1
  k2: v2

示例代码

1.pom导入配置文件提示spring-boot-configuration-processor

	<dependencies>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-configuration-processor</artifactId>
		</dependency>
	</dependencies>

2.读取application.yml配置

application.yml配置文件
# 单个key value 写法
color: blue

# 对象写法1
# student: {name: lily,age: 22,fromShenSheng: false}
# 对象写法2
student:
  name: lily
  age: 22
  fromShenSheng: false
  # list集合写法1
  petList: [,,兔子]
  # list集合写法2
  hobby-list:
    - 唱歌
    - 跳舞
    - 运动
  # map集合写法1
  identity: {home: 孩子, school: 学生}
  # map集合写法2
  plainList:
    morning: 上课
    afternoon: 午休
    night: 自习
    
Student.java实体类代码
@Data
@Component
@ConfigurationProperties(prefix = "student")
public class Student {

    private String name;
    private String age;
    private Boolean fromShenSheng;
    @Value("${color}")
    private String color;

    private List<String> petList;
    private List<String> hobbyList;

    /**身份*/
    private Map<String,Object> identity;
    /**计划安排清单**/
    private Map<String,Object> plainList;

}
测试调用

/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/17 13:57
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationTest {
    ObjectMapper objectMapper=new ObjectMapper();

    @Autowired
    Student student;

    /**
     * 加载yml
     * @throws Exception
     */
    @Test
    public void testYml() throws Exception {
        System.out.println("单个key value:"+objectMapper.writeValueAsString(student.getColor()));
        System.out.println("对象信息:"+objectMapper.writeValueAsString(student));
    }
}

3.读取application.properties配置

application.properties文件
color=blue

student-property.name=猿份哥
student-property.age=18
student-property.fromShenSheng=true
student-property.petList=猫1,狗2,兔子3
student-property.hobbyList=唱歌,唱歌,唱歌
student-property.identity.home=孩子
student-property.identity.school=学生
student-property.plainList.morning=上课
student-property.plainList.afternoon=午休
student-property.plainList.night=自习
StudentProperties.java实体类代码
/**
 * 加载properties文件
 */
@Data
@Component
@ConfigurationProperties(prefix = "student-property")
public class StudentProperties {

    private String name;
    private String age;
    private Boolean fromShenSheng;
    @Value("${color}")
    private String color;

    private List<String> petList;
    private List<String> hobbyList;

    /**身份*/
    private Map<String,Object> identity;
    /**计划安排清单**/
    private Map<String,Object> plainList;

}
测试调用

/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/17 13:57
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationTest {
    ObjectMapper objectMapper=new ObjectMapper();

    @Autowired
    StudentProperties studentProperties;
    
    /**
     * 加载properties
     * @throws Exception
     */
    @Test
    public void testProperties() throws Exception {
        System.out.println("对象信息:"+objectMapper.writeValueAsString(studentProperties));
    }
}

4.读取外部properties文件

resource目录下新增stu-external.properties文件
color=blue

stu.name=猿份哥
stu.age=18
stu.fromShenSheng=true
stu.petList=猫1,狗2,兔子3
stu.hobbyList=唱歌,唱歌,唱歌
stu.identity.home=孩子
stu.identity.school=学生
stu.plainList.morning=上课
stu.plainList.afternoon=午休
stu.plainList.night=自习

ExternalStuProperties.java实体类代码
@Data
@Component
@Configuration
@PropertySource(value= {"classpath:stu-external.properties"},encoding = "utf-8")
@ConfigurationProperties(prefix = "stu")
public class ExternalStuProperties implements Serializable {

    private String name;
    private String age;
    private Boolean fromShenSheng;
    @Value("${color}")
    private String color;

    private List<String> petList;
    private List<String> hobbyList;

    /**身份*/
    private Map<String,Object> identity;
    /**计划安排清单**/
    private Map<String,Object> plainList;

}

测试调用
/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/17 13:57
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationTest {
    ObjectMapper objectMapper=new ObjectMapper();
    @Autowired
    ExternalStuProperties externalStuProperties;
    /**
     * 加载外部properties
     * @throws Exception
     */
    @Test
    public void testExternalProperties() throws Exception {
        System.out.println("加载外部properties:"+ externalStuProperties);
    }
}

5.读取外部yml文件

resource目录下新增application-external.yml文件
# 单个key value 写法
color: blue

# 对象写法1
# student: {name: lily,age: 22,fromShenSheng: false}
# 对象写法2
external:
  name: 猿份哥
  age: 22
  fromShenSheng: false
  # list集合写法1
  petList: [,,兔子]
  # list集合写法2
  hobby-list:
    - 唱歌
    - 跳舞
    - 运动
  # map集合写法1
  identity: {home: 孩子, school: 学生}
  # map集合写法2
  plainList:
    morning: 上课
    afternoon: 午休
    night: 自习

ExternalStuYml.java实体类代码
@Data
@Component
@Configuration
@ConfigurationProperties(prefix = "external")
public class ExternalStuYml implements Serializable {

    private String name;
    private String age;
    private Boolean fromShenSheng;
    @Value("${color}")
    private String color;

    private List<String> petList;
    private List<String> hobbyList;

    /**身份*/
    private Map<String,Object> identity;
    /**计划安排清单**/
    private Map<String,Object> plainList;

}

测试调用
/**
 * @author 猿份哥
 * @description
 * @createTime 2019/8/17 13:57
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class ConfigurationTest {
    ObjectMapper objectMapper=new ObjectMapper();
    @Autowired
    ExternalStuYml externalStuYml;
    
    /**
     * 加载外部yml
     * 如:application-external.yml需要在application中配置
     * spring:
     *   profiles:
     *     include: external
     * @throws Exception
     */
    @Test
    public void testExternalYml() throws Exception {
        //需要在application中配置
        System.out.println("加载外部yml:"+ externalStuYml);
    }
}
加载外部yml时需要配置spring.profiles.include=external加入容器,或者bean中配置需要加载的yml文件(springboot新版本此配置已失效参见下面最新加载外部yaml文件)
@SpringBootApplication
public class Start{
    public static void main(String[] args) {
        SpringApplication.run(Start.class, args);
    }
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
        yaml.setResources(new ClassPathResource("application-external.yml"));
        configurer.setProperties(yaml.getObject());
        return configurer;
    }
}

最新加载外部yaml文件

1.定义MyEnvironmentPostProcessor.java

public class MyEnvironmentPostProcessor implements EnvironmentPostProcessor {

    private final YamlPropertySourceLoader loader = new YamlPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        Resource path = new ClassPathResource("external-application.yml");
        PropertySource<?> propertySource = loadYaml(path);
        environment.getPropertySources().addLast(propertySource);
    }
    private PropertySource<?> loadYaml(Resource path) {
        Assert.isTrue(path.exists(), () -> "Resource " + path + " does not exist");
        try {
            return this.loader.load("custom-resource", path).get(0);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Failed to load yaml configuration from " + path, ex);
        }
    }
}

2.resources/META-INF 文件夹下创建spring.factories文件配置好MyEnvironmentPostProcessor

org.springframework.boot.env.EnvironmentPostProcessor=com.yuanfenge.loading.MyEnvironmentPostProcessor

最后不管对你有没有用,猿份哥还是为你准备了一份完整的代码,万一您想去看看呢!哈哈哈

https://github.com/tiankonglanlande/springboot/tree/master/springboot-configuration-yml-properties

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot系列14-加载yml,properties配置文件信息 的相关文章

随机推荐