【Spring】——15、使用@PropertySource加载配置文件

时间:2022-12-15 14:19:51

【Spring】——15、使用@PropertySource加载配置文件

????作者简介:zhz小白
公众号:小白的Java进阶之路
专业技能:
1、Java基础,并精通多线程的开发,熟悉JVM原理
2、熟悉Java基础,并精通多线程的开发,熟悉JVM原理,具备⼀定的线上调优经验
3、熟悉MySQL数据库调优,索引原理等,⽇志原理等,并且有出过⼀篇专栏
4、了解计算机⽹络,对TCP协议,滑动窗⼝原理等有⼀定了解
5、熟悉Spring,Spring MVC,Mybatis,阅读过部分Spring源码
6、熟悉SpringCloud Alibaba体系,阅读过Nacos,Sentinel,Seata,Dubbo,Feign,Gateway核⼼源码与设计,⼆次开发能⼒
7、熟悉消息队列(Kafka,RocketMQ)的原理与设计
8、熟悉分库分表ShardingSphere,具有真实⽣产的数据迁移经验
9、熟悉分布式缓存中间件Redis,对其的核⼼数据结构,部署架构,⾼并发问题解决⽅案有⼀定的积累
10、熟悉常⽤设计模式,并运⽤于实践⼯作中
11、了解ElasticSearch,对其核⼼的原理有⼀定的了解
12、了解K8s,Jekins,GitLab
13、了解VUE,GO
14、⽬前有正在利⽤闲暇时间做互游游戏,开发、运维、运营、推销等

本人著作git项目:https://gitee.com/zhouzhz/star-jersey-platform,有兴趣的可以私聊博主一起编写,或者给颗star
领域:对支付(FMS,FUND,PAY),订单(OMS),出行行业等有相关的开发领域
????如果此文还不错的话,还请????关注、点赞、收藏三连支持????一下博主~

1、PropertySource介绍

通过@PropertySource注解可以将properties配置文件中的key/value存储到Spring的Environment中,Environment接口提供了方法去读取配置文件中的值,参数是properties配置文件中定义的key值。

其源代码如下:
【Spring】——15、使用@PropertySource加载配置文件

细心的朋友,应该发现其里面还有个@PropertySources注解了吧,是不是跟@ComponentScan一样了,具体的大家可以回顾前面讲的@ComponentScan的详解,他就是个复用注解,代表我们的@PropertySource可以用多个。
【Spring】——15、使用@PropertySource加载配置文件

2、使用

  • PropertySource
    • 添加 PropertySource
      • context:property-placeholder
      • PropertySourcesPlaceholderConfigurer
        • PropertyPlaceholderConfigurer
      • @PropertySource
      • @PropertySources
  • Spring Boot 中的 @ConfigurationProperties
    • 可以将属性绑定到结构化对象上
    • ⽀持 Relaxed Binding
    • ⽀持安全的类型转换
    • @EnableConfigurationProperties
  • 定制 PropertySource
    • 主要步骤
      • 实现 PropertySource
      • 从 Environment 取得 PropertySources
      • 将⾃⼰的 PropertySource 添加到合适的位置
    • 切⼊位置
      • EnvironmentPostProcessor
      • BeanFactoryPostProcessor

作用:可以用于读取配置文件,比如我们正常的nacos就是用这个做的。

2.1、pom

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zhz</groupId>
    <artifactId>spring-boot-property-source-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-boot-property-source-demo</name>
    <description>Spring Boot集成PropertySource</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.2、yml

resource/yapf.properties

spring.boot.zhz.property.source=hello

resource/META-INF/spring.factories

org.springframework.boot.env.EnvironmentPostProcessor=com.zhz.springbootpropertysourcedemo.processor.YapfEnvironmentPostProcessor

2.3、后置处理器

package com.zhz.springbootpropertysourcedemo.processor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.boot.env.PropertiesPropertySourceLoader;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

/**
 * @author zhouhengzhe
 * @Description: TODO
 * @sign: 代码虐我千百遍,我视代码如初恋
 * @date 2021/8/25上午12:51
 */
@Slf4j
public class YapfEnvironmentPostProcessor implements EnvironmentPostProcessor {
    private PropertiesPropertySourceLoader loader=new PropertiesPropertySourceLoader();

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) {
        MutablePropertySources propertySources = environment.getPropertySources();
        Resource resource = new ClassPathResource("yapf.properties");
        try {
            PropertySource ps = loader.load("YetAnotherPropertiesFile", resource).get(0);
            propertySources.addFirst(ps);
        } catch (Exception e) {
            log.error("Exception!", e);
        }
    }
}

2.4、启动类

package com.zhz.springbootpropertysourcedemo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author mac
 */
@Slf4j
@SpringBootApplication
public class SpringBootPropertySourceDemoApplication implements ApplicationRunner {

    @Value("${spring.boot.zhz.property.source}")
    private String propertySource;

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

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("{}",propertySource);
    }
}

【Spring】——15、使用@PropertySource加载配置文件