Skip to content

Spring Boot 扩展自定义 PropertySource 解析 JSON 配置文件

Spring Boot 提供了强大的配置管理功能,支持多种格式的配置文件(如 .properties 和 .yml)。然而,在某些情况下,我们可能希望使用 JSON 格式的配置文件来存储配置信息。本文将介绍如何通过自定义 PropertySource 来实现这一需求,并提供一个完整的示例。

.properties、.yml 文件实现的原理

@PropertySource 注解如下

java
@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;
}

可以看出 properties,yml 解析主要是依靠 PropertySourceFactory 这个接口来实现的, 默认提供了 DefaultPropertySourceFactory 的实现,所以 .properties、.yml 主要也是通过这个类去实现, 为了实现解析 json,那么我们就需要实现 PropertySourceFactory 的方法。步骤如下

创建自定义的 PropertySourceFactory

首先,我们需要创建一个类来实现 PropertySourceFactory 接口,并重写 createPropertySource 方法来处理 JSON 文件。

java
public class JsonPropertySourceFactory implements PropertySourceFactory {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public PropertySource<?> createPropertySource( String name, EncodedResource resource) throws IOException {
        Map<String,Object> map = objectMapper.readValue(resource.getInputStream(), Map.class);
        return new MapPropertySource((name != null ? name: resource.getResource().getFilename()), map);
    }
}

定义属性配置类

创建一个配置类,并使用 @PropertySource 注解来指定 JSON 配置文件的位置和自定义的 PropertySourceFactory。

java
@Component
@Data
@PropertySource(value = "classpath:propertysource/config.json",factory = JsonPropertySourceFactory.class)
public class JsonConfigProperties {

    @Value("${app.name}")
    private String name;

    @Value("${app.description}")
    private String description;

}

创建 config.json

根据上述的 PropertySource 指定结构在 resource 目录下创建 propertysource 目录,然后创建 config.json 文件,json 内容如下

json
{
  "app.name": "test",
  "app.description": "hello,json format"
}

验证属性是否注入成功

我们通过实现 CommandLineRunner 接口来输出属性内容来验证是否注入成功

java
@Slf4j
@Component
public class AppInit implements CommandLineRunner {

    private final JsonConfigProperties jsonConfigProperties;

    public AppInit(JsonConfigProperties jsonConfigProperties) {
        this.jsonConfigProperties = jsonConfigProperties;
    }

    @Override
    public void run(String... args) throws Exception {
        log.info("read config json {}",jsonConfigProperties);
    }
}

启动应用,查看控制台可以看到有以下打印内容

text
read config json JsonConfigProperties(name=test, description=hello,json format)

总结

通过自定义 PropertySourceFactory 和 @PropertySource 注解,我们可以轻松地在 Spring Boot 项目中使用 JSON 格式的配置文件。这不仅增加了配置管理的灵活性,还使得配置文件的结构更加清晰和易于维护。

Released under the MIT License.