0 背景
SpringBoot项目为基础,docker打包项目,docker-compose用.yml部署项目,一些灵活项配置在app.yml(自定义名称)文件中。例如经常变动的文件就需要外挂在服务器路径下(与项目docker容器里的路径是一一对应的关系)。例如灵活配置的地址。本文以这两种情况为例,记录配置过程。
1 首先,定义配置类
配置类 ApplicationProperties
import org.springframework.boot.context.properties.ConfigurationProperties;
/**
* Properties specific to Epidemic.
* <p>
* Properties are configured in the {@code application.yml} file.
* See {@link io.github.jhipster.config.JHipsterProperties} for a good example.
*/
@ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) //这里的"application"为prod.yml里配置项名称
public class ApplicationProperties {
private String basePath; //配置文件地址
private String mapUrl; //配置url地址
public String getBasePath() {
return basePath;
}
public void setBasePath(String basePath) {
this.basePath = basePath;
}
public String getMapUrl() {
return mapUrl;
}
public void setMapUrl(String mapUrl) {
this.mapUrl = mapUrl;
}
}
在启动类上添加@EnableConfigurationProperties 注解,并配置ApplicationProperties类
@EnableConfigurationProperties({ApplicationProperties.class})
在项目里的prod.yml文件中,配置项
application:
basePath: ${BASE_PATH}
mapUrl: ${MAP_URL}
2 配置app.yml文件
volumes为外挂文件路径配置项: /mnt/data/epidemic/file/为文件在服务器的地址
environment为项目环境配置项:BASE_PATH和MAP_URL与 prod.yml里对应
version: '2'
services:
epidemic-app:
image: epidemic
volumes:
- /mnt/data/epidemic/file/:/root/epidemic/ // /mnt/data/epidemic/file/为文件外挂路径
environment:
- _JAVA_OPTIONS=-Xmx512m -Xms256m
- SPRING_PROFILES_ACTIVE=prod,swagger
- MANAGEMENT_METRICS_EXPORT_PROMETHEUS_ENABLED=true
- SPRING_DATASOURCE_URL=jdbc:mysql://172.26.4.13:3336/epidemic?useUnicode=true&characterEncoding=utf8&useSSL=false&allowMultiQueries=true
- JHIPSTER_SLEEP=30 # gives time for other services to boot before the application
- BASE_PATH=/root/epidemic/
- MAP_URL=http://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineCommunity/MapServer //灵活配置url
ports:
- 9988:9966
epidemic-mysql:
extends:
file: mysql.yml
service: epidemic-mysql
3 代码里自定义路径(扩展)
一般来说,文件来自于不同的路径。因此,外挂文件时,可能需要自定义路径,一般以menu的方式定义。
public enum FileType {
Epidemic("疫情数据"){
@Override
public String path() {
return "epidemic";
}
},
MapPoint("经纬度"){
@Override
public String path() {
return "mapPoint";
}
};
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
FileType(String description){
this.description = description;
}
public abstract String path();
}
调用时
String path = Paths.get(properties.getBasePath(), FileType.Epidemic.path()).toString();