Spring6 探析之@PropertySource 注解

发布时间 2023-05-26 21:02:16作者: acdongla

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