Spring注解驱动开发三切换环境Profile

简介: Spring注解驱动开发三切换环境Profile

@Profile注解

Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能。指定组件在哪个环境的情况下才能被注册到容器中,不指定则任何环境下都能注册这个组件。



可以通过如下四种方式指定Bean生效的环境。

ConfigurableEnvironment.setActiveProfiles
AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME =spring.profiles.active
web.xml配置
@ActiveProfiles注解

接口类如下:

@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();
}


① 如果不加@Profile注解,则该bean在任何环境下都被注入

@Bean
public Yellow yellow(){
  return new Yellow();
}

② 如果指定了@Profile,则只有该环境被激活的时候bean才会被注入

@Profile("dev")
@Bean("devDataSource")
public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  dataSource.setUser(user);
  dataSource.setPassword(pwd);
  dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/xian");
  dataSource.setDriverClass(driverClass);
  return dataSource;
}

③ 如果指定了@Profile(“default”),那么默认环境下bean会被注入

@Profile("default")
@Bean("testDataSource")
public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
  ComboPooledDataSource dataSource = new ComboPooledDataSource();
  dataSource.setUser(user);
  dataSource.setPassword(pwd);
  dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
  dataSource.setDriverClass(driverClass);
  return dataSource;
}



④ 如果@Profile配置于类上,则该类下的bean想起作用,Spring激活的环境首先要与类配置@Profile指定的环境一致,其次再看类中方法上的@Profile注解配置。

@PropertySource("classpath:/dbconfig.properties")
@Profile("dev")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
  @Value("${db.user}")
  private String user;
  private StringValueResolver valueResolver;
  private String  driverClass;
  @Bean
  public Yellow yellow(){
    return new Yellow();
  }
  @Profile("default")
//  @Profile("test")
  @Bean("testDataSource")
  public DataSource dataSourceTest(@Value("${db.password}")String pwd) throws Exception{
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setUser(user);
    dataSource.setPassword(pwd);
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test");
    dataSource.setDriverClass(driverClass);
    return dataSource;
  }
  @Profile("dev")
  @Bean("devDataSource")
  public DataSource dataSourceDev(@Value("${db.password}")String pwd) throws Exception{
    ComboPooledDataSource dataSource = new ComboPooledDataSource();
    dataSource.setUser(user);
    dataSource.setPassword(pwd);
    dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/xian");
    dataSource.setDriverClass(driverClass);
    return dataSource;
  }
}

激活环境的几种方式

① 虚拟机参数


② 代码激活

@Test
public void test01(){
  //1、创建一个applicationContext
  AnnotationConfigApplicationContext applicationContext = 
      new AnnotationConfigApplicationContext();
  //2、设置需要激活的环境
  applicationContext.getEnvironment().setActiveProfiles("dev");
  //3、注册主配置类
  applicationContext.register(MainConfigOfProfile.class);
  //4、启动刷新容器
  applicationContext.refresh();
  String[] namesForType = applicationContext.getBeanNamesForType(DataSource.class);
  for (String string : namesForType) {
    System.out.println(string);
  }
  Yellow bean = applicationContext.getBean(Yellow.class);
  System.out.println(bean);
  applicationContext.close();
}

③ web.xml

<!-- 在上下文中设置profile的默认值 -->
<context-param>
    <param-name>spring.profiles.default</param-name>
    <param-value>dev</param-value>
</context-param>
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 在servlet中设置profile的默认值 -->
    <init-param>
     <param-name>spring.profiles.default</param-name>
     <param-value>dev</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>





相关实践学习
每个IT人都想学的“Web应用上云经典架构”实战
本实验从Web应用上云这个最基本的、最普遍的需求出发,帮助IT从业者们通过“阿里云Web应用上云解决方案”,了解一个企业级Web应用上云的常见架构,了解如何构建一个高可用、可扩展的企业级应用架构。
MySQL数据库入门学习
本课程通过最流行的开源数据库MySQL带你了解数据库的世界。 &nbsp; 相关的阿里云产品:云数据库RDS MySQL 版 阿里云关系型数据库RDS(Relational Database Service)是一种稳定可靠、可弹性伸缩的在线数据库服务,提供容灾、备份、恢复、迁移等方面的全套解决方案,彻底解决数据库运维的烦恼。 了解产品详情:&nbsp;https://www.aliyun.com/product/rds/mysql&nbsp;
目录
相关文章
|
10月前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
8431 122
|
10月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
10月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
795 2
|
11月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
1577 128
|
11月前
|
XML Java 数据格式
常用SpringBoot注解汇总与用法说明
这些注解的使用和组合是Spring Boot快速开发和微服务实现的基础,通过它们,可以有效地指导Spring容器进行类发现、自动装配、配置、代理和管理等核心功能。开发者应当根据项目实际需求,运用这些注解来优化代码结构和服务逻辑。
688 12
|
11月前
|
传感器 Java 数据库
探索Spring Boot的@Conditional注解的上下文配置
Spring Boot 的 `@Conditional` 注解可根据不同条件动态控制 Bean 的加载,提升应用的灵活性与可配置性。本文深入解析其用法与优势,并结合实例展示如何通过自定义条件类实现环境适配的智能配置。
590 0
探索Spring Boot的@Conditional注解的上下文配置
|
11月前
|
智能设计 Java 测试技术
Spring中最大化@Lazy注解,实现资源高效利用
本文深入探讨了 Spring 框架中的 `@Lazy` 注解,介绍了其在资源管理和性能优化中的作用。通过延迟初始化 Bean,`@Lazy` 可显著提升应用启动速度,合理利用系统资源,并增强对 Bean 生命周期的控制。文章还分析了 `@Lazy` 的工作机制、使用场景、最佳实践以及常见陷阱与解决方案,帮助开发者更高效地构建可扩展、高性能的 Spring 应用程序。
415 0
Spring中最大化@Lazy注解,实现资源高效利用
|
11月前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
1141 1
使用Spring的@Retryable注解进行自动重试
|
11月前
|
安全 数据可视化 Java
AiPy开发的 Spring 漏洞检测神器,未授权访问无所遁形
针对Spring站点未授权访问问题,现有工具难以检测如Swagger、Actuator等组件漏洞,且缺乏修复建议。全新AI工具基于Aipy开发,具备图形界面,支持一键扫描常见Spring组件,自动识别未授权访问风险,按漏洞类型标注并提供修复方案,扫描结果可视化展示,支持导出报告,大幅提升渗透测试与漏洞定位效率。
|
11月前
|
Java 测试技术 编译器
@GrpcService使用注解在 Spring Boot 中开始使用 gRPC
本文介绍了如何在Spring Boot应用中集成gRPC框架,使用`@GrpcService`注解实现高效、可扩展的服务间通信。内容涵盖gRPC与Protocol Buffers的原理、环境配置、服务定义与实现、测试方法等,帮助开发者快速构建高性能的微服务系统。
1891 0

热门文章

最新文章