一、为什么会想到定义@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. LeetCode 21. Merge Two Sorted Lists合并两个有序链表 (C++)

    题目: Merge two sorted linked lists and return it as a new list. The new list should be made by splici ...

  2. USACO 利润Profits

    洛谷P3009 [USACO11JAN]利润Profits 题解  https://www.luogu.org/problemnew/solution/P3009 JDOJ 2727: USACO 2 ...

  3. Arduino SPI驱动7引脚0.96寸OLED SSD1306 调试笔记

    https://www.geek-workshop.com/thread-37818-1-1.html 2.下载最新库https://learn.adafruit.com/monoc ... ibra ...

  4. Linux性能优化实战学习笔记:第三十七讲

    一.上节回顾 上一节,我带你一起学习了网络性能的评估方法.简单回顾一下,Linux 网络基于 TCP/IP协议栈构建,而在协议栈的不同层,我们所关注的网络性能也不尽相同. 在应用层,我们关注的是应用程 ...

  5. 第02组 Alpha冲刺(6/6)

    队名:無駄無駄 组长博客 作业博客 组员情况 张越洋 过去两天完成了哪些任务 准备"Alpha事后诸葛亮" 提交记录(全组共用) 接下来的计划 完善接口文档 调动组员积极性 还剩下 ...

  6. SpringBoot集成Spring Security(3)——异常处理

    源码地址:https://github.com/jitwxs/blog_sample 文章目录 一.常见异常二.源码分析三.处理异常不知道你有没有注意到,当我们登陆失败时候,Spring securi ...

  7. MySQL-InnoDB-MVCC多版本并发控制

    一.MySQL可重复读级别下,因为MVCC引起的BUG,下图1为相应的Java代码,其中事务1的生命周期最长,循环开启的事务2.3.4...与事务1并行 ,数据的读取只会成功一次,后面的读不到新增数据 ...

  8. java包学习之JDBC

    public class DemoJDBC { public static void main(String[] args) throws ClassNotFoundException, SQLExc ...

  9. BizTalk证书相关操作

    OPEN SSL 神技能 从PFX文件中导出私钥 openssl pkcs12 -in Cert.pfx -nocerts -nodes -out private_pc.key 从PFX文件中导出CS ...

  10. jquery取消绑定的方法

    jquery取消绑定的方法 一般用变量控制 不要用unbind() 相应比较慢 <pre> $('.choseitem').on('click', function () { //如果设置 ...