功能
在spring-boot項目啟動時,將會打印項目的基本信息:服務名稱,pom中的項目版本,以及jar包構建的時間,方便檢測服務是否更新到正確的版本,也可以提供接口訪問
實現(xiàn)步驟(steps 2)
step 1 添加服務啟動的前置執(zhí)行代碼
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import javax.annotation.PostConstruct;
/**
* 初始化bean之前執(zhí)行即服務啟動的前置代碼
*/
@Configuration
@Slf4j
public class BeanPostConfig implements BeanPostProcessor {
@Value("${project.version}")
private String serviceVersion;
@Value("${project.builddate}")
private String serviceBuildDate;
@Value("${spring.application.name}")
private String serviceName;
@Autowired
private Environment environment;
@PostConstruct
public void projectInfo(){
StringBuffer projectInfo = new StringBuffer();
projectInfo.append("\n=================project=================\n");
projectInfo.append(String.format("\nservice name:%s\n",serviceName));
projectInfo.append(String.format("\nservice version:%s\n",serviceVersion));
projectInfo.append(String.format("\nservice build date:%s\n",serviceBuildDate));
projectInfo.append("\n=================project=================\n");
log.info(projectInfo.toString());
}
}
step 2 application.yml配置變量
project:
version: @project.version@
builddate: @maven.build.timestamp@
注意獲取maven的變量是使用@@斑鼻,并且在@Value中使用@@是無效的,bootstrap.yml也無效,具體原理以后在了解一下