- 目录结构
-
application.yml
server: port: 8081 # 引入其他的配置文件 spring: profiles: include: - dict1 - dict2
-
application-dict1.yml
test01: var01: username: zhangsan age: 20 var02: this is string
-
cn.king.demo01.properties.Demo01Properties
package cn.king.demo01.properties; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.PropertySource; import org.springframework.stereotype.Component; import java.util.Map; /** * @author: wjl@king.cn * @time: 2020/11/23 22:45 * @version: 1.0.0 * @description: yml封装map或者对象 */ // 必须有getter/setter @Data // 必须加@Component @Component // 指定引用哪个配置文件中的数据. 我们在application.yml中使用了spring.profiles.include后下面的注解可以不写 @PropertySource(value = {"classpath:application-dict1.yml"}, encoding = "UTF-8") @ConfigurationProperties(prefix = "test01") public class Demo01Properties { // 注意, 封装对象不能使用@Value // 注意, 成员变量名要和配置文件中配置的参数名一致 private Map<String, String> var01; private String var02; }
-
cn.king.demo01.Demo01ApplicationTests
package cn.king.demo01; import cn.king.demo01.properties.Demo01Properties; import lombok.extern.slf4j.Slf4j; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; @Slf4j @SpringBootTest class Demo01ApplicationTests { @Resource private Demo01Properties demo01Properties; @Test void test01() { demo01Properties.getVar01().forEach((k, v) -> log.info(k + "--" + v)); log.info("--------------"); log.info(demo01Properties.getVar02()); } }
-
pom.xml
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency>