spring.config.location启动的参数不互补可以使用spring.config.additional-location

星期六, 2021-11-27 | Author: Lee | JAVA-and-J2EE, linux | 1,278 views

0.先说下springboot版本为2.5.7,location的会优先使用不再使用打包文件中的配置文件
详情见官方文档:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#features.external-config.files
解决办法是:

    java -jar -Dspring.config.location=/apps/config/app.properties /app/serverless/app.jar &
  ###替换一下即可
    java -jar -Dspring.config.additional-location=/apps/config/app.properties /app/serverless/app.jar &

1.起因需要给应用加上build time和version对应的版本号

这些参数可以在mvn的时候直接生成出来,但是在配置文件中将无法配置

先把这个做下记录

2.在pom.xml文件的properties中添加如下内容

 
  <properties>
        <maven.build.timestamp.format>yyyy-MM-dd HH:mm:ss</maven.build.timestamp.format>
        <!--maven.build.timestamp保存了maven编译时间戳-->
        <timestamp>${maven.build.timestamp}</timestamp>
</properties>
 
### 在pom.xml的build中添加如下内容,使properties能取到pom.xml中的数据
<resources>
       <resource>
           <directory>src/main/resources/</directory>
           <filtering>true</filtering>
       </resource>
</resources>

3.在springboot的配置文件中新增

app.name=pomelo
app.build_time=@timestamp@
app.version=@project.version@

4.在spring 应用中使用即可获取打包时间及版本代码如下:

package com.pomelolee.controller;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
 
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
public class AppController {
 
  @Value("${app.build_time:}")
  private String buildTime;
 
  @Value("${app.name:}")
  private String appName;
 
  @Value("${app.version:}")
  private String version;
 
  @RequestMapping("/version")
  public @ResponseBody String showJarTime() {
    Map<String, String> data = new LinkedHashMap<>();
    data.put("appName", appName);
    data.put("version", version);
    data.put("buildTime", toChinaTime(buildTime));
    return JSON.toJSONString(data);
  }
 
  private String toChinaTime(String date) {
    if (StringUtils.isBlank(date)) {
      return date;
    }
    Date oldDate = null;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    try {
      oldDate = sdf.parse(date);
      Calendar cal = Calendar.getInstance();
      cal.setTime(oldDate);
      cal.add(Calendar.HOUR_OF_DAY, +8);
      return sdf.format(new Date(cal.getTimeInMillis()));
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }
}

5.以前启动应用的换成spring.config.additional-location即可互补,否则spring.config.location为替换
使用的springboot为2.5.7版本,解决见最上0即可

Tags: ,

文章作者: Lee

本文地址: https://www.pomelolee.com/2240.html

除非注明,Pomelo Lee文章均为原创,转载请以链接形式标明本文地址

No comments yet.

Leave a comment

Search

文章分类

Links

Meta