@PropertySource注解使用详情

简介: @PropertySource注解使用详情
日积月累,水滴石穿 😄

前言

Spring Boot中,默认加载的配置文件名称为 application.properties 或者为 application.yml。会将属性文件的值加载到 SpringEnvironment中。可以使用 @Value
@ConfigurationProperties 进行取值。

application.properties application.yml我们可以称为主配置文件,但是在实际开发中,我们不可能将所有的配置放在主配置文件中,日积月累,主配置文件就会越来越庞大,难以维护。所以需要进行拆分,比如数据库配置、redis配置、微信配置,我们可以分别拆分为:datasource.properties(yml)redis.propertieswx.properties

可惜我们自定义的配置文件并不会被自动加载,我们需要使用 Spring 提供的 @PropertySource 注解,去加载指定的配置文件。

依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.2.1.RELEASE</version>
</dependency>

未使用注解

配置文件

小杰提供了两个配置文件,application.propertiesjuejin.properties,文件内容如下:

  • application.properties
blog.name = cxyxj
  • juejin.properties
juejin.home = https://juejin.cn/user/2164257578290398

测试

@SpringBootApplication(scanBasePackages = "com.cxyxj.propertysource")
public class AppMain {

    public static void main(String[] args) {
        ConfigurableApplicationContext application = SpringApplication.run(AppMain.class);
        //获得容器的 Environment
        Environment env = application.getEnvironment();
        //根据key获取
        String blog = env.getProperty("blog.name");
        String juejin = env.getProperty("juejin.home");
        System.out.println(blog);
        System.out.println(juejin);
    }
}
结果:
cxyxj
null

看到juejin.home并没有被加载到 Environment对象中。

使用注解加载指定properties

  • 启动类加上如上注解,并指定配置文件地址
@PropertySource("juejin.properties")
  • 启动结果
cxyxj
https://juejin.cn/user/2164257578290398

@PropertySource注解定义

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Repeatable(PropertySources.class)
public @interface PropertySource {
    String name() default "";

    String[] value();

    boolean ignoreResourceNotFound() default false;

    String encoding() default "";

    Class<? extends PropertySourceFactory> factory() default PropertySourceFactory.class;
}

先来看一下PropertySource类上的注解,一共有四个, @Target@Retention@Documented这三个是元注解,不过多介绍。还有一个是 @Repeatable,它有什么作用呢?如果我们希望一个注解在一个类上重复标注,可以在注解上加 @Repeatable。效果如下:

image-20220125200104828

接下来看看注解中的属性。

  • name:指明此属性源的名称。 如果省略,将根据属性源生成一个名称。

    • value:要加载的属性文件的资源位置。支持 propertiesXML 的属性文件格式 ,例如:classpath:/cn/cxyxj/xx.propertiesfile:/path/xxx.xml注意:不允许使用资源位置通配符(例如 **/*.properties);
  • ignoreResourceNotFound:指定的属性文件如果不存在,是否要忽略错误。默认为 false,也就是属性文件不存在,则会抛出异常。该属性是 Spring4.0 新增的。
  • encoding:指定资源文件的编码格式。不指定则使用文件默认的编码格式。该属性是 Spring4.3 新增的。
  • factory:指定自定义 PropertySourceFactory,默认使用 DefaultPropertySourceFactory

加载指定xml文件

  • 先创建一个名为 juejin.xml的xml 文件,内容如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <entry key="juejin.home">https://juejin.cn/user/2164257578290398</entry>
</properties>
  • @PropertySource注解修改如下:
@PropertySource(name = "juejin", value = {"juejin.xml"})
  • 启动结果
cxyxj
https://juejin.cn/user/2164257578290398

加载 yml

上面说过,@PropertySource只支持 propertiesXML 的属性文件格式,这肯定是不行的,现在yml越来越流行了。那如何让@PropertySource支持 yml文件格式呢?这时候就需要使用到 factory属性了,指定 PropertySourceFactory 进行加载。

  • 创建名为 juejin.yml的文件
juejin:
  home: https://juejin.cn/user/2164257578290398
  • 创建YmlPropertyResourceFactory类,并实现 PropertySourceFactory,重写 createPropertySource方法。
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.List;
import java.util.Optional;

/**
 * 在 @PropertySource 注解的 factory属性指定 YmlPropertyResourceFactory 类,则可以支持读取 yml
 * @author: cxyxj
 * @create: 2022-01-21 15:35
 */
public class YmlPropertyResourceFactory implements PropertySourceFactory {

    private static String YML = ".yml";
    private static String YAML = ".yaml";
    /**
     *
     * @param name:@PropertySource 注解 name 的值
     * @param resource:资源
     */
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        // 文件名称
        String filename = resource.getResource().getFilename();
        // 属性源的名称
        String resourceName = Optional.ofNullable(name).orElse(filename);
        if (filename.endsWith(YML) || filename.endsWith(YAML)) {
            List<PropertySource<?>> yamlSources = new YamlPropertySourceLoader().load(resourceName, resource.getResource());
            return yamlSources.get(0);
        } else {
            // 其他文件后缀
            return new DefaultPropertySourceFactory().createPropertySource(name, resource);
        }
    }
}
  • 修改@PropertySource
@PropertySource(name = "juejin", value = {"juejin.yml"},factory = YmlPropertyResourceFactory.class)
  • 启动效果
cxyxj
https://juejin.cn/user/2164257578290398

  • 如你对本文有疑问或本文有错误之处,欢迎评论留言指出。如觉得本文对你有所帮助,欢迎点赞和关注。
相关文章
|
Java 数据库连接 mybatis
mybatismybatisPlus Update操作返回值不是影响行数
mybatismybatisPlus Update操作返回值不是影响行数
1283 0
|
Kubernetes 应用服务中间件 nginx
k8s ingress不生效的bug 解决了。
k8s ingress不生效的bug 解决了。
640 0
|
小程序 Linux 区块链
Python PyInstaller 打包成 Win、Mac 应用程序(app / exe)
Python PyInstaller 打包成 Win、Mac 应用程序(app / exe)
6162 0
|
传感器 监控 Java
如何正确理解 CPU 使用率和平均负载的关系?看完你就知道了
CPU(Central Processing Unit)是计算机系统的运算和控制核心,是信息处理、程序运行的最终执行单元,相当于系统的“大脑”。
4149 0
如何正确理解 CPU 使用率和平均负载的关系?看完你就知道了
|
10月前
|
存储 边缘计算 人工智能
基于阿里云边缘计算(ENS)的智能安防系统开发与部署
随着物联网和人工智能技术的发展,智能安防成为保障公共和企业安全的重要手段。阿里云边缘计算(ENS)提供低延迟、高可靠的计算能力,支持实时处理海量数据。本文介绍如何基于阿里云边缘计算开发并部署智能安防系统,涵盖视频监控、人脸识别、异常行为检测等功能,并通过实战案例展示其核心优势与最佳实践。
|
Java 编译器 测试技术
全面理解Maven Compiler Plugin-Maven编译插件
【10月更文挑战第16天】
3011 1
|
Web App开发 数据库 索引
Playwright 测试并行性
Playwright 测试并行性
514 0
|
JavaScript
vue实战——404页面模板001——男女手电筒动画
vue实战——404页面模板001——男女手电筒动画
247 1
|
JSON 负载均衡 Java
SpringCloud Feign 远程调用(史上最详细讲解)
SpringCloud Feign 远程调用(史上最详细讲解)
14750 0
SpringCloud Feign 远程调用(史上最详细讲解)
|
SQL HIVE Python
Window10 pyhive连接hive报错:Could not start SASL: b‘Error in sasl_client_start (-4) SASL(-4)
Window10 pyhive连接hive报错:Could not start SASL: b‘Error in sasl_client_start (-4) SASL(-4)
903 0
Window10 pyhive连接hive报错:Could not start SASL: b‘Error in sasl_client_start (-4) SASL(-4)

热门文章

最新文章