判断程序当前运行环境_Java

Ashe / 2023-08-18 / 原文

首先需要在application.yml中指定你的环境类型

也可以在bootstrap.yml中指定,不过从 Spring Boot 2.4 版本开始,不再支持 bootstrap.ymlbootstrap.properties 文件

spring:
  config:
    activate:
      on-profile: dev
  banner:
    location: banner/dev.txt

---
spring:
  config:
    activate:
      on-profile: test
  banner:
    location: banner/test.txt

---
spring:
  config:
    activate:
      on-profile: prod
  banner:
    location: banner/prod.txt

使用工具类判断

@Component
public class EnvironmentUtils {

    private static final String DEV = "dev";
    private static final String TEST = "test";
    private static final String PROD = "prod";
    private final Environment environment;

    public EnvironmentUtils(Environment environment) {
        this.environment = environment;
    }

    public String getCurrentProfile() {
        String[] activeProfiles = environment.getActiveProfiles();

        if (activeProfiles.length > 0) {
            return activeProfiles[0];
        }

        return null;
    }

    public boolean isDev() {
        String currentProfile = getCurrentProfile();
        return DEV.equals(currentProfile);
    }

    public boolean isTest() {
        String currentProfile = getCurrentProfile();
        return TEST.equals(currentProfile);
    }

    public boolean isProd() {
        String currentProfile = getCurrentProfile();
        return PROD.equals(currentProfile);
    }

}

使用示例

    @ExceptionHandler(value = EmergencyException.class)
    public ResponseEntity<String> catchException(EmergencyException e) {
        // 记录日志
        log.error(e.getTitle(), e);
        // 通知运维
        // 通知开发
        if (environmentUtils.isProd()) {
            // 生产环境才通知程序员
            ExceptionAlarm.noticeDeveloper(e.getMessage(), e.getDeveloper(), e.getTitle());
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("系统异常,已通知开发人员");
    }

如果你也在application.yml指定自定义banner的话,那么启动项目时,就不再是SpringBoot自带的Banner,而是你自定义的Banner

Banner设计网站推荐http://patorjk.com/software/taag

Banner文件分享

自定义Banner后,项目启动效果