Spring6 探析之@PropertySource 注解

Spring6 探析之@PropertySource 注解

介绍

@PropertySource 注解用于加载配置类,在使用 Spring 时,我们可以使用 @PropertySource 注解将自定义的配置文件加载到 Spring 中,方便我们的自定义的开发

下面是 @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;

}

可以看到,该注解只能标注在类上,它有以下参数

  • name: 可为空,表示配置文件的名字
  • value: 配置文件的路径
  • ignoreResourceNotFound: 配置文件是否可以找不到,默认不可以——找不到会报错
  • encoding: 配置文件的编码,注意,默认非 utf-8
  • factory:读取配置文件的工厂类,默认是 PropertySourceFactory

我们再看一下 @PropertySources 注解的源码,它可以包含多个 @PropertySource 注解

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PropertySources {

	PropertySource[] value();

}

使用

在 resources 目录下创建配置文件 config.properties,里面有如下内容

image-20230526205429906

创建配置类,使用 @PropertySource 注解加载配置文件

image-20230526205513445

拿到配置文件的内容并打印出来

image-20230526205534421

image-20230526205542544

本文作者:yangruomao

本文链接:https://www.cnblogs.com/yangruomao/p/17435802.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   yangruomao  阅读(65)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起