一、为什么会想到定义@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. Aliyun STS Java SDK示例

    package com.aliyun.oss.demo; import com.aliyuncs.DefaultAcsClient; import com.aliyuncs.exceptions.Cl ...

  2. How to display `top` results sorted by memory usage in real time?

    If you're using the top that comes with Ubuntu (top -v = procps-ng version 3.3.10), then you can use ...

  3. Apex 小知识:SOQL 在循环中的应用

    两种在循环中引用 SOQL 的方法 第一种方法: List<Account> accounts = [SELECT Id FROM Account WHERE NumberOfEmploy ...

  4. ESP8266 LUA脚本语言开发: 准备工作-LUA文件加载与变量调用

    前言 这节说一下多个文件调用 多个文件之间变量调用 准备两个文件 init.lua other.lua 开始 模块默认一开始调用的是init.lua 咱让init.lua调用 other.lua 很简 ...

  5. 在 C++ 中使用 QML 对象

    看过了如何在 QML 中使用 C++ 类型或对象,现在来看如何在 C++ 中使用 QML 对象. 我们可以使用 QML 对象的信号.槽,访问它们的属性,都没有问题,因为很多 QML 对象对应的类型,原 ...

  6. linux _文件目录与权限

    1. 目录相关 . 代表次层目录 .. 代表上一层目录 - 代表前一个工作目录 ~ 代表目前使用者身份所在home目录 ~account 代表account这个使用者的home目录 cd 切换目录(c ...

  7. layer弹出框,zIndex不断增加的问题

    针对layer弹出框每次进行弹出操作时z-index不断加1的问题,手动设置过zIndex值不管用,每次关闭时清空layer对象也不管用. 解决办法: 修改layer.js,,将红框代码改为绿框代码, ...

  8. Extra:Cg Math Functions

    常用Cg函数 数学函数 abs(x):绝对值 // float类型的实现 float abs(float x) { return max(-a, a); } sin(x):正弦,输入为弧度 // fl ...

  9. CentOS升级Python2.6到Python2.7并安装pip[转载]

    貌似CentOS 6.X系统默认安装的Python都是2.6版本的?平时使用以及很多的库都是要求用到2.7版本或以上,所以新系统要做的第一件事必不可少就是升级Python啦!在这里做个简单的升级操作记 ...

  10. Python转义序列

    正则表达式参考:https://www.cnblogs.com/huxi/archive/2010/07/04/1771073.html