知识改变命运! SpringBoot系列14-加载yml,properties配置文件信息_猿份哥-lskyf博客社区

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

猿份哥 1年前 ⋅ 2082 阅读 ⋅ 0 个赞

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


全部评论: 0

    我有话说:

    Spring Boot系列8-使用jasypt加密配置文件内容简单版

    文章目录 1.为什么配置文件需要加密 2.首先引入pom依赖文件 3.在application.properties或者application.yml文件配置加密密码 4.获取加密内容例如:我想

    SpringBoot系列10-文件上传

    文章目录 1.先来最简单的 2.设置文件大小,请求大小 3.多文件上传 怎样使用最简单的方式上传文件,如何上传多个文件呢 先来最简单的 pom.xml文件引入依赖文件 <

    java高频面试题-java类需要经历哪些过程?

    本篇文章是基于JDK 8及以上版本的Java类过程。 Java类过程 Java类是Java虚拟机(JVM)执行过程中的关键步骤。它涉及Java类的动态、链接和初始化。在本文中,我们将

    SpringBoot系列9-使用jasypt自定义stater运行时动态传入加密密码

    文章目录 1.新建springboot-encryption-configuration项目实现stater 2.pom文件引入jasypt 3.在resources/support/下配置

    SpringBoot系列15-mysql-multiple-data-sources1

    springboot 多数据源的一个简单示例 多数据源分包 新建数据库test1和表tbl_user CREATE TABLE `tbl_user` ( `id` int(11) NOT

    Spring Boot系列1-helloword

      使用springboot简单轻松创建helloword SpringBoot系列1-helloword 关于springboot这是摘自官方的一段话 Spring Boot

    Spring Boot系列7-SpringBoot+mybatis+druid+TypeHandler

    介绍在SpringBoot中集成mybatis和druid以及自定义TypeHandler 创建数据库表 SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; -- --------------------...

    Spring Boot系列6-SpringBoot中使用servlet

    介绍在SpringBoot中如何使用servlet pom.xml <dependency> <groupId>org.springframework.boot<

    SpringBoot系列16-Spring boot2x快速整合swagger2(Open Api3注解版)

    前言:为什么要使用swagger 传统的web开发,前端和后端的HTTP接口文档交互都是使用word文档记录,存在不仅限于这些问题;不能时时更新,不易于传输etc. swagger2可以使用配置文件

    SpringBoot系列12-redis-pipeline keys模糊查询替代方案

    keys模糊查询遇到性能问题redis cup 99%以及解决方案 之前写过一篇文章 《java redis通过key模糊删除,批量删除,批量查询相关数据》,在项目中我也是这样使用的。刚开始还没有

    Spring Boot系列2-全局统一异常处理

    原创: 天空和唯美 天空唯美  点击查看原文 为什么要全局统一异常处理呢?如果系统发生了异常,不做统一异常处理,前端会给用户展示一大片看不懂的文字。做统一异常处理后当

    SSD和HDD能否共存于一个系统中?

    优势: SSD提供了快速的启动和应用程序时间...

    spring boot系列4-定时任务-springboot自带的scheduled超级简单

    需求:创建一个每天凌晨0点执行的定时任务1.创建任务 /** * @author 天空蓝蓝的 */ @Slf4j @EnableScheduling @Component public class MyTask { @Async @Schedul...

    Spring Boot系列5-定时任务-springboot整合quartz实现动态定时任务

    MyJob实现Job接口,重写execute方法在里面操作我们要执行的业务逻辑。 @Slf4j public class MyJob implements Job { @Autowired private MyService myService;...

    加入公众号
    加入公众号