SpringBoot @PropertySource 使用详解

版权申诉
0 下载量 76 浏览量 更新于2024-08-08 收藏 18KB DOCX 举报
"SpringBoot系列之PropertySource用法的简介" 在SpringBoot应用中,管理配置文件是至关重要的任务。默认情况下,SpringBoot会自动加载`application.yml`或`application.properties`中的配置信息。然而,当项目发展到一定规模时,可能会需要将不同领域的配置分开管理,这时就需要引入额外的配置文件。`@PropertySource`注解正是为此目的设计的,它允许我们从其他外部属性文件中加载配置。 `@PropertySource`是Spring框架提供的一个注解,用于指示Spring容器从指定的资源位置加载属性源。在SpringBoot中,这个注解仍然有效,但它通常与`@ConfigurationProperties`结合使用,以便更方便地绑定和映射属性值到Java对象。 首先,我们创建一个名为`user.properties`的外部配置文件,其中包含一些用户相关的属性: ``` user.userName=root user.isAdmin=true user.regTime=2019/11/01 user.isOnline=1 user.maps.k1=v1 user.maps.k2=v2 user.lists=list1,list2 user.address.tel=15899988899 user.address.name=上海 ``` 接下来,我们需要在Java类上使用`@PropertySource`注解来指示Spring加载这个外部文件。同时,使用`@ConfigurationProperties`注解,我们可以将属性文件中的键值对映射到一个Java Bean中,使得这些配置更加结构化和易于管理。下面是一个示例Bean: ```java package org.muses.jeeplatform.bean; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; import java.util.Map; @Component @PropertySource("classpath:user.properties") @ConfigurationProperties(prefix = "user") public class UserProperties { private String userName; private boolean isAdmin; private Date regTime; private int isOnline; private Map<String, String> maps; private List<String> lists; private Address address; // getters and setters public static class Address { private String tel; private String name; // getters and setters } } ``` 在上述代码中,`UserProperties`类包含了与`user.properties`文件中的各个属性相对应的字段。`@ConfigurationProperties(prefix = "user")`指定了属性前缀,这意味着Spring将会寻找以"user."开头的所有属性,并将它们映射到这个类的相应字段上。 通过这种方式,我们可以轻松地将不同的配置分离到各自的文件中,然后通过`@PropertySource`和`@ConfigurationProperties`组合使用,将这些配置整合到我们的应用程序中。这种方法既保持了代码的整洁,又提高了配置的可维护性。同时,由于`@Component`注解,这个类会作为Spring的一个bean注册,因此可以在其他地方通过依赖注入来使用这些配置属性。
2023-06-10 上传