一、为什么会想到定义@SpringCloudProfile这样的注解

首页提一下@Profile注解:它主要用与Spring Boot多环境配置中,指定某个类只在指定环境中生效,比如swagger的配置只允许开发和测试环境开发,线上需要禁止使用。

使用@Profile进行如下配置:

@Configuration
@EnableSwagger2
@Profile({"dev", "test"})
public class Swagger2Config { @Bean
public Docket docket() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
//当前包路径
.apis(RequestHandlerSelectors.basePackage("com.zbq.springbootbase.controller"))
.paths(PathSelectors.any()).build(); } //构建api文档的详细信息函数
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//页面标题
.title("springboot-base-frame,使用Swagger2构建RESTful API")
//创建人
.contact(new Contact("张波清", "756623607@qq.com", ""))
//版本号
.version("1.0")
//描述
.description("API 描述")
.build(); } }

但是在Spring Cloud中由于使用了配置中心,导致启动项目时没有指定spring.profiles.active属性导致@Profile注解失效,原因就是@Profile通过获取环境变量中spring.profiles.active属性值,与注解中设置的值进行比较,包含就生效。

所有在Spring Cloud中需要换一个环境变量来实现,正好有spring.cloud.config.profile这个变量,该变量用于指定读取配置中心那个环境配置的,一般有这些值,dev、test、prod

二、自定义@SpringCloudProfile注解的实现

1)定义@SpringCloudProfile注解

/**
* @author zhangboqing
* @date 2019/11/12
*/
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(SpringCloudProfileCondition.class)
public @interface SpringCloudProfile { /**
* The set of profiles for which the annotated component should be registered.
*/
String[] value(); }

2)实现SpringCloudProfileCondition类,用于条件匹配

/**
* @author zhangboqing
* @date 2019/11/12
*/
public class SpringCloudProfileCondition implements Condition { public static final String ACTIVE_PROFILES_PROPERTY_NAME = "spring.cloud.config.profile"; @Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(SpringCloudProfile.class.getName());
if (attrs != null) {
for (Object value : attrs.get("value")) {
if (acceptsProfiles(context,(String[]) value)) {
return true;
}
}
return false;
}
return true;
} public boolean acceptsProfiles(ConditionContext context,String... profiles) {
Assert.notEmpty(profiles, "Must specify at least one profile");
for (String profile : profiles) {
if (StringUtils.hasLength(profile) && profile.charAt() == '!') {
if (!isProfileActive(context,profile.substring())) {
return true;
}
}
else if (isProfileActive(context,profile)) {
return true;
}
}
return false;
} protected boolean isProfileActive(ConditionContext context,String profile) {
validateProfile(profile);
String property = context.getEnvironment().getProperty(ACTIVE_PROFILES_PROPERTY_NAME);
return property.equals(profile);
} protected void validateProfile(String profile) {
if (!StringUtils.hasText(profile)) {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must contain text");
}
if (profile.charAt() == '!') {
throw new IllegalArgumentException("Invalid profile [" + profile + "]: must not begin with ! operator");
}
}
}

【Spring Cloud】Spring Cloud之自定义@SpringCloudProfile注解实现@Profile注解的功能的更多相关文章

  1. 小伙伴们在催更Spring系列,于是我写下了这篇注解汇总!!

    大家好,我是冰河~~ 由于在更新其他专题的文章,Spring系列文章有很长一段时间没有更新了,很多小伙伴都在公众号后台留言或者直接私信我微信催更Spring系列文章. 看来是要继续更新Spring文章 ...

  2. Spring Boot + Spring Cloud 实现权限管理系统 (Spring Security 版本 )

    技术背景 到目前为止,我们使用的权限认证框架是 Shiro,虽然 Shiro 也足够好用并且简单,但对于 Spring 官方主推的安全框架 Spring Security,用户群也是甚大的,所以我们这 ...

  3. Spring Boot + Spring Cloud 实现权限管理系统 后端篇(二十五):Spring Security 版本

    在线演示 演示地址:http://139.196.87.48:9002/kitty 用户名:admin 密码:admin 技术背景 到目前为止,我们使用的权限认证框架是 Shiro,虽然 Shiro ...

  4. Spring Boot + Spring Cloud 实现权限管理系统 后端篇(十九):服务消费(Ribbon、Feign)

    技术背景 上一篇教程中,我们利用Consul注册中心,实现了服务的注册和发现功能,这一篇我们来聊聊服务的调用.单体应用中,代码可以直接依赖,在代码中直接调用即可,但在微服务架构是分布式架构,服务都运行 ...

  5. 新书上线:《Spring Boot+Spring Cloud+Vue+Element项目实战:手把手教你开发权限管理系统》,欢迎大家买回去垫椅子垫桌脚

    新书上线 大家好,笔者的新书<Spring Boot+Spring Cloud+Vue+Element项目实战:手把手教你开发权限管理系统>已上线,此书内容充实.材质优良,乃家中必备垫桌脚 ...

  6. (6)java Spring Cloud+Spring boot+mybatis企业快速开发架构之SpringCloud-Spring Boot项目详细搭建步骤

    ​ 在 Spring Tools 4 for Eclipse 中依次选择 File->New->Maven Project,然后在出现的界面中按图所示增加相关信息. ​ <paren ...

  7. spring Boot+spring Cloud实现微服务详细教程第二篇

    上一篇文章已经说明了一下,关于spring boot创建maven项目的简单步骤,相信很多熟悉Maven+Eclipse作为开发常用工具的朋友们都一目了然,这篇文章主要讲解一下,构建spring bo ...

  8. spring Boot+spring Cloud实现微服务详细教程第一篇

    前些天项目组的大佬跟我聊,说项目组想从之前的架构上剥离出来公用的模块做微服务的开发,恰好去年的5/6月份在上家公司学习了国内开源的dubbo+zookeeper实现的微服务的架构.自己平时对微服务的设 ...

  9. Spring MVC & Boot & Cloud 技术教程汇总(长期更新)

    昨天我们发布了Java成神之路上的知识汇总,今天继续. Java成神之路技术整理(长期更新) 以下是Java技术栈微信公众号发布的关于 Spring/ Spring MVC/ Spring Boot/ ...

随机推荐

  1. 洛谷 U87052 一线天

    洛谷 U87052 一线天 题目传送门 题目背景 \(JDFZ\)即将举办第一届"一线天"趣味运动会...... 题目描述 "一线天"运动会在\(JLU\)南岭 ...

  2. C# 集合根据属性去重筛选

    1.单个属性去重筛选 //去重筛选 var ChgDtlVoList = datas.Where((x, i) => datas.FindIndex(z => z.ChgId == x.C ...

  3. Tiling Terrace CodeForces - 1252J(dp、贪心)

    Tiling Terrace \[ Time Limit: 1000 ms\quad Memory Limit: 262144 kB \] 题意 给出一个字符串 \(s\),每次可以选择三种类型来获得 ...

  4. 记一次排错经历,requests和fake_useragent

    在部署tornado项目上线时, 首次重启服务后第一次请求必然会报错, 后续的就能正常访问, 长报错urllib.error.URLError,如图排查多次依然发现不了问题 报的最多的依然是上图中的错 ...

  5. Spring Boot中的Mongodb多数据源扩展

    在日常工作中,我们通过Spring Data Mongodb来操作Mongodb数据库,在Spring Boot中只需要引入spring-boot-starter-data-mongodb即可. 然后 ...

  6. Eureka工作原理分析

    demo源码地址:https://github.com/flyingJiang/SpringCloud 首先,单独使用Eureka. Eureka整合Ribbon 未完待续……

  7. java web开发入门九(Maven使用&idea创建maven项目)基于intellig idea

    Maven 1.解决的问题 jar包的依赖和管理:版本.依赖关系等 自动构建项目 2.maven介绍 1.Maven是什么? Apache Maven是一个软件项目管理的综合工具.基于项目对象模型(P ...

  8. kafka的安装和初步使用

    简介 最近开发的项目中,kafka用的比较多,为了方便梳理,从今天起准备记录一些关于kafka的文章,首先,当然是如何安装kafka了. Apache Kafka是分布式发布-订阅消息系统. Apac ...

  9. 非替代品,MongoDB与MySQL对比分析

    IT168 评论]对于只有SQL背景的人来说,想要深入研究NoSQL似乎是一个艰巨的任务,MySQL与MongoDB都是开源常用数据库,但是MySQL是传统的关系型数据库,MongoDB则是非关系型数 ...

  10. 运维开发实践——基于Sentry搭建错误日志监控系统

    错误日志监控也可称为业务逻辑监控, 旨在对业务系统运行过程中产生的错误日志进行收集归纳和监控告警.似乎有那么点曾相识?没错... 就是提到的“APM应用性能监控”.但它又与APM不同,APM系统主要注 ...