sprintboot读取自定义配置文件properties、yml、yaml,环境springboot2.4.4

简介: 我这里使用的是springboot2.4.4的版本,其他版本自测

我这里使用的是springboot2.4.4的版本,其他版本自测


在要赋值的Bean类上面添加注解,prefix是你配置的前缀


@ConfigurationProperties(prefix = "alipay")

再添加注解,注意是@PropertySource 不是@PropertySources,最后没有s


@PropertySource(value = {"classpath:alipay.properties"})

然后添加@Comment注解添加到IOC容器中,使用@Autowired或者@Resource注解注入使用




如果是yml或yaml的配置文件


就添加一个格式转换的类,如下

import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
public class YamlAndPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null) {
            return super.createPropertySource(name, resource);
        }
        Resource resourceResource = resource.getResource();
        if (!resourceResource.exists()) {
            return new PropertiesPropertySource(null, new Properties());
        } else if (resourceResource.getFilename().endsWith(".yml") || resourceResource.getFilename().endsWith(".yaml")) {
            List<PropertySource<?>> sources = new YamlPropertySourceLoader().load(resourceResource.getFilename(), resourceResource);
            return sources.get(0);
        }
        return super.createPropertySource(name, resource);
    }
}


然后把@PropertySource中添加一个factory属性


@PropertySource(factory = YamlAndPropertySourceFactory.class,value = {"classpath:yml/alipay.yaml"})


相关文章
|
19天前
|
XML Java 数据格式
Springboot中自定义组件
Springboot中自定义组件
|
19天前
|
关系型数据库 MySQL 数据库
第十四章 演示MYSQL自定义values.yaml绑定PV和PVC和数据库用户密码
第十四章 演示MYSQL自定义values.yaml绑定PV和PVC和数据库用户密码
33 0
|
19天前
|
Java 调度 Spring
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
SpringBoot实现多线程定时任务动态定时任务配置文件配置定时任务
292 0
|
19天前
|
安全 Java Spring
SpringBoot2 | SpringBoot监听器源码分析 | 自定义ApplicationListener(六)
SpringBoot2 | SpringBoot监听器源码分析 | 自定义ApplicationListener(六)
53 0
|
19天前
|
Java 容器 Spring
SpringBoot:详解依赖注入和使用配置文件
SpringBoot:详解依赖注入和使用配置文件
|
19天前
|
缓存 Java Sentinel
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
Springboot 中使用 Redisson+AOP+自定义注解 实现访问限流与黑名单拦截
|
19天前
|
Java 数据库 数据安全/隐私保护
【SpringBoot】Validator组件+自定义约束注解实现手机号码校验和密码格式限制
【SpringBoot】Validator组件+自定义约束注解实现手机号码校验和密码格式限制
199 1
|
17天前
|
Java
Springboot 使用自定义注解结合AOP方式校验接口参数
Springboot 使用自定义注解结合AOP方式校验接口参数
Springboot 使用自定义注解结合AOP方式校验接口参数
|
19天前
|
前端开发 Java
SpringBoot之自定义注解参数校验
SpringBoot之自定义注解参数校验
25 2
|
19天前
|
Java 容器 Spring
【SpringBoot:详解依赖注入和使用配置文件】
【SpringBoot:详解依赖注入和使用配置文件】
17 2

热门文章

最新文章