目录
1、加载多个配置文件
-
需求描述1:
项目中需要根据功能配置多个配置文件,保存相关的信息,如,application-ftp.yml 保存ftp相关的信息,application-redis.yml 保存redis的配置信息
-
项目结构:
-
详细配置:
新建3个配置文件,application-config.yml、application-ftp.yml、application-redis.yml,可以根据项目实际情况建立配置文件,需要注意的是,文件名要以application- 开头。
-
配置yml
配置application.yml
server:
port: 8084
spring:
profiles:
include: config,ftp,redis
配置application-config.yml
#配置项目中的其他配置值
config:
value: config
配置application-ftp.yml
#配置ftp的信息,下载上传路径等
ftp:
user: user
password: 123456
配置application-redis.yml
#配置redis的相关信息
redis:
name: redis
password: 1234
-
测试:
新建测试类,测试能否获取多配置文件的值:
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @description
* @create: 2020-01
**/
@Slf4j
@RestController
public class TestApplicationYmlsController {
@Value("${config.value}")
private String config;
@Value("${ftp.user}")
private String ftpUser;
@Value("${ftp.password}")
private String ftpPassword;
@Value("${redis.name}")
private String redisUser;
@Value("${redis.password}")
private String redisPassword;
@RequestMapping("/test")
public String testYml() {
log.info("config:{},ftpUser:{},ftpPassword:{},redisUser:{},redisPassword:{}",config,ftpUser,ftpPassword,redisUser,redisPassword);
return "success";
}
}
postman 接口测试 http://127.0.0.1:8084/test:
查看后台日志,配置文件中的值可以正常取出来:
2、获取配置文件中的数组值
-
需求描述2:
配置文件application.yml 中存在如下结构,需要获取各个ip:
provinceConf:
smpIp:
- 192.168.2.164
- 192.168.2.166
-
实现方式:
新建配置类:
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @description
* @create: 2020-01-19
**/
@Data
@Component
@ConfigurationProperties(prefix = "provinceconf")
public class YmlListValueConfig {
private String [] smpIp;
}
-
测试:
在以上测试类中注入获取数组值的配置类,接口调用测试:
结果: