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

本文涉及的产品
RDS MySQL DuckDB 分析主实例,集群系列 4核8GB
RDS AI 助手,专业版
RDS MySQL DuckDB 分析主实例,基础系列 4核8GB
简介: 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;
目录
相关文章
|
4月前
|
人工智能 运维 Java
Spring AI Alibaba Admin 开源!以数据为中心的 Agent 开发平台
Spring AI Alibaba Admin 正式发布!一站式实现 Prompt 管理、动态热更新、评测集构建、自动化评估与全链路可观测,助力企业高效构建可信赖的 AI Agent 应用。开源共建,现已上线!
5793 82
|
5月前
|
缓存 监控 Java
SpringBoot @Scheduled 注解详解
使用`@Scheduled`注解实现方法周期性执行,支持固定间隔、延迟或Cron表达式触发,基于Spring Task,适用于日志清理、数据同步等定时任务场景。需启用`@EnableScheduling`,注意线程阻塞与分布式重复问题,推荐结合`@Async`异步处理,提升任务调度效率。
877 128
|
5月前
|
XML 安全 Java
使用 Spring 的 @Aspect 和 @Pointcut 注解简化面向方面的编程 (AOP)
面向方面编程(AOP)通过分离横切关注点,如日志、安全和事务,提升代码模块化与可维护性。Spring 提供了对 AOP 的强大支持,核心注解 `@Aspect` 和 `@Pointcut` 使得定义切面与切入点变得简洁直观。`@Aspect` 标记切面类,集中处理通用逻辑;`@Pointcut` 则通过表达式定义通知的应用位置,提高代码可读性与复用性。二者结合,使开发者能清晰划分业务逻辑与辅助功能,简化维护并提升系统灵活性。Spring AOP 借助代理机制实现运行时织入,与 Spring 容器无缝集成,支持依赖注入与声明式配置,是构建清晰、高内聚应用的理想选择。
618 0
|
5月前
|
Java 测试技术 API
将 Spring 的 @Embedded 和 @Embeddable 注解与 JPA 结合使用的指南
Spring的@Embedded和@Embeddable注解简化了JPA中复杂对象的管理,允许将对象直接嵌入实体,减少冗余表与连接操作,提升数据库设计效率。本文详解其用法、优势及适用场景。
374 126
|
4月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
6月前
|
XML JSON Java
Spring框架中常见注解的使用规则与最佳实践
本文介绍了Spring框架中常见注解的使用规则与最佳实践,重点对比了URL参数与表单参数的区别,并详细说明了@RequestParam、@PathVariable、@RequestBody等注解的应用场景。同时通过表格和案例分析,帮助开发者正确选择参数绑定方式,避免常见误区,提升代码的可读性与安全性。
|
6月前
|
前端开发 Java API
利用 Spring WebFlux 技术打造高效非阻塞 API 的完整开发方案与实践技巧
本文介绍了如何使用Spring WebFlux构建高效、可扩展的非阻塞API,涵盖响应式编程核心概念、技术方案设计及具体实现示例,适用于高并发场景下的API开发。
524 0
|
4月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
566 2
|
5月前
|
Java 测试技术 数据库
使用Spring的@Retryable注解进行自动重试
在现代软件开发中,容错性和弹性至关重要。Spring框架提供的`@Retryable`注解为处理瞬时故障提供了一种声明式、可配置的重试机制,使开发者能够以简洁的方式增强应用的自我恢复能力。本文深入解析了`@Retryable`的使用方法及其参数配置,并结合`@Recover`实现失败回退策略,帮助构建更健壮、可靠的应用程序。
693 1
使用Spring的@Retryable注解进行自动重试