@Profile bean环境隔离

先看一段配置

spring:
  main:
# 允许名称相同的bean相互覆盖
    allow-bean-definition-overriding: true
  profiles:
# 当前环境是dev
    active: dev

多环境支持的依赖是org.springframework.cloud:spring-cloud-context
如果引入了com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery则不用引入了,原因是依赖传递

像上面的配置之后我们的配置文件可能还有像bootstrap-dev.yml``bootstrap-release.yml这样命名的配置文件

这些配置文件就是用于区分多环境配置的配置文件主要看横线后面的

好,到现在已经做到了配置的环境隔离。如果想要bean在不同的环境也不同呢?

这时候@Profile就登场了,惯例先看源码😁

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Conditional(ProfileCondition.class)
public @interface Profile {

	/**
	 * The set of profiles for which the annotated component should be registered.
	 */
	String[] value();

}

The @Profile annotation may be used in any of the following ways:

  • as a type-level annotation on any class directly or indirectly annotated with @Component, including @Configuration classes
  • as a meta-annotation, for the purpose of composing custom stereotype annotations
  • as a method-level annotation on any @Bean method

以上说明来自源码

说明了注解@Profile可以用来那些地方
从源码的@Target({ElementType.TYPE, ElementType.METHOD})也可以知晓
该注解可以用在类、接口、枚举、注解、方法上

Indicates that a component is eligible for registration when one or more specified profiles are active.
意思是当一个或多个指定的配置文件处于活动状态的时候符合注册条件
符合什么注册条件呢?答案是:bean的注册条件

如何使用呢?再看一些代码
spring.profiles.active=dev

/**
 * @author YinShangWen
 * @since 2023/2/18 10:47
 */
public interface DemoService {
}
/**
 * @author YinShangWen
 * @since 2023/2/18 10:49
 */
@Service
@Profile("dev")
public class DemoServiceImplDev implements DemoService {
}
/**
 * @author YinShangWen
 * @since 2023/2/18 10:49
 */
@Service
@Profile("release")
public class DemoServiceImpl implements DemoService {
}

这时候如果运行起来beanDemoServiceImpl还是DemoServiceImplDev呢?
这里就要看@Profile的value是什么了,像上面配置了spring.profiles.active=dev那么注册的就是携带注解@Profile("dev")bean也就是DemoServiceImplDev

到这里基本使用就完成了
不知道有没有同学思考一个问题,如果想上面类似的代码很多的时候是不是每次都需要写@Profile("xxx")
有时候一不小心把value中的内容写错一个字母就会出现找不到bean的bug了

怎么解决呢?也比较简单,就是用@Profile("xxx")修饰一个注解然后我们使用的时候就用自定义出来的注解就行了。废话不多说看代码

/**
 * @author YinShangWen
 * @since 2023/2/18 9:34
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Profile("release")
public @interface Release {
}
/**
 * @author YinShangWen
 * @since 2023/2/18 9:39
 */
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Profile({"dev", "uat"})
public @interface Dev {
}

这里我定义了两个自定义注解分别是ReleaseDev
用途分别是在环境是release 的时候注册和环境是devuat的时候注册
如何使用?大致用法和@Profile差不多就是省略了写value。
这样就可以避免上面说到的粗心的问题了

完😏

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值