获取Profile名称

127 阅读1分钟

通常项目区分不同的环境会有多份配置文件,生产和测试,甚至于本地环境都有一定的差别。有时候需要根据activeProfile来做一些特殊处理。获取方式如下:

/**
 * activeProfile 工具类
 * */
@Component
public class ProfileUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    /**
     * 获取第一个activeProfile 否则返回空字符
     * @return profile name
     * */
    public static String getFirstActiveProfile() {
        String[] profiles = context.getEnvironment().getActiveProfiles();
        if (null != profiles) {
            return profiles[0];
        }
        return null;
    }
}