SpringBoot如何通过@Profile注解配置多环境

 更新时间:2023年06月13日 09:15:02   作者:fengyehongWorld  
在Spring中,可以使用配置文件的方式来指定不同环境下所需要的配置信息,本文给大家介绍SpringBoot如何通过@Profile注解配置多环境,感兴趣的朋友跟随小编一起看看吧

一. 使用场景

在Spring中,可以使用配置文件的方式来指定不同环境下所需要的配置信息

⏹application.yml

spring:
  profiles:
  	# 通过active来指定当前所处的开发环境
    active: dev

⏹application-dev.yml

spring:
  datasource:
    url: jdbc:mysql://localhost/myblog-dev
    username: dev
    password: mysql
    driver-class-name: com.mysql.cj.jdbc.Driver

⏹application-product.yml

spring:
  datasource:
    url: jdbc:mysql://localhost/myblog-product
    username: product
    password: mysql
    driver-class-name: com.mysql.cj.jdbc.Driver

但有时候,我们不通过配置文件,而是通过配置类的方式来指定不同环境下的配置信息,
此时就需要用到@Profile注解

二. 前期准备

⏹用来封装数据库信息的Entity

import lombok.Builder;
import lombok.Data;
@Builder
@Data
public class DBInfoEntity {
    private String url;
    private String port;
    private String userName;
    private String password;
}

⏹配置接口

public interface Config {
	// 获取数据库信息
    DBInfoEntity getDBInfo();
	// 获取系统URL
    String getSystemUrl();
}

三. @Profile注解作用于类上

  • 我们使用@Profile注解分别作用于如下所示的两个配置类上,分别指定devproduct环境下才能起作用。
  • 我们通过@Configuration注解指定两个配置类的Bean名称都是MyConfig,一般情况下会报错,因为Spring的IOC容器中,Bean的名称是唯一的,但是我们使用了@Profile注解指定了开发环境,不满足指定开发环境的配置类不会被添加到Bean中,所以不会报错。

3.1 配置类

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration("MyConfig")
// 指定开发环境为dev
@Profile("dev")
public class MyConfig1 implements Config {
    @Override
    public DBInfoEntity getDBInfo() {
        return DBInfoEntity.builder()
                .url("https://127.0.0.1")
                .port("8080")
                .userName("devUser")
                .password("110120")
                .build();
    }
    @Override
    public String getSystemUrl() {
        return "https://www.dev.com";
    }
}
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration("MyConfig")
// 指定开发环境为product
@Profile("product")
public class MyConfig2 implements Config {
    @Override
    public DBInfoEntity getDBInfo() {
        return DBInfoEntity.builder()
                .url("https://127.0.0.2")
                .port("8089")
                .userName("prodUser")
                .password("999000")
                .build();
    }
    @Override
    public String getSystemUrl() {
        return "https://www.prod.com";
    }
}

3.2 效果

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class Test32Controller implements CommandLineRunner {
	// 注入接口,会自动从IOC容器中获取该接口的实现类
    @Autowired
    private Config config;
    @Override
    public void run(String... args) throws Exception {
        DBInfoEntity dbInfo = config.getDBInfo();
        System.out.println(dbInfo);
        String systemUrl = config.getSystemUrl();
        System.out.println(systemUrl);
    }
}

💪💪💪dev环境

💪💪💪product环境

四. @Profile注解作用于方法上

4.1 定义一个生产环境的注解

@Profile注解作用于自定义注解上时,自定义注解便可标识开发环境,相当于是@Profile(“开发环境名称”)的简写方式。

import org.springframework.context.annotation.Profile;
import java.lang.annotation.*;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
@Profile("product")
public @interface ProductionAnnotation {
}

4.2 配置类

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
@Configuration
public class MyConfig3 {
	// 开发环境时,才会注入IOC容器
    @Bean
    @Profile("dev")
    public String getNameDev() {
        return "devName";
    }
	// 生产环境时,才会注入IOC容器
    @Bean
    @ProductionAnnotation  // 相当于 @Profile("product")
    public String getNameProduct() {
        return "productName";
    }
}

4.3 效果

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
@Component
public class Test32Controller implements CommandLineRunner {
    @Autowired
    private ApplicationContext applicationContext;
    @Override
    public void run(String... args) throws Exception {
        // 判断当前IOC容器中是否存在名称为 getNameDev 的Bean
        boolean getNameDevExist = applicationContext.containsBean("getNameDev");
        if (getNameDevExist) {
            // 从IOC容器中获取出名称为 getNameDev 的Bean
            Object bean1 = applicationContext.getBean("getNameDev");
            System.out.println("目前所在的是开发环境!");
            System.out.println(bean1);
        }
        boolean getNameProductExist = applicationContext.containsBean("getNameProduct");
        if (getNameProductExist) {
            Object bean2 = applicationContext.getBean("getNameProduct");
            System.out.println("目前所在的是生产环境!");
            System.out.println(bean2);
        }
    }
}

💪💪💪dev环境

💪💪💪product环境

参考资料

Springboot中的@Profile注解

到此这篇关于SpringBoot 通过@Profile注解配置多环境的文章就介绍到这了,更多相关SpringBoot 配置多环境内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • java类访问权限与成员访问权限解析

    java类访问权限与成员访问权限解析

    这篇文章主要针对java类访问权限与成员访问权限进行解析,对类与成员访问权限进行验证,感兴趣的小伙伴们可以参考一下
    2016-02-02
  • 深入了解Java设计模式之职责链模式

    深入了解Java设计模式之职责链模式

    Java设计模式中有很多种类别,例如单例模式、装饰模式、观察者模式等。本文将为大家详细介绍其中的职责链模式,感兴趣的可以了解一下
    2022-09-09
  • Spring Boot整合tk.mybatis代码实例

    Spring Boot整合tk.mybatis代码实例

    这篇文章主要介绍了Spring Boot整合tk.mybatis代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • HashMap和List遍历方法及如何遍历删除元素总结

    HashMap和List遍历方法及如何遍历删除元素总结

    在本篇文章中小编给大家分享了关于HashMap和List遍历方法及如何遍历删除元素知识点总结,需要的朋友们参考下。
    2019-05-05
  • 一文详解Springboot集成mybatis-plus

    一文详解Springboot集成mybatis-plus

    这篇文章主要介绍了Mybatis-Plus与SpringBoot整合,并在项目中实战运用,列举其增删改查的使用方式,对学习或工作有一定的帮助,需要的小伙伴可以参考阅读
    2023-04-04
  • springboot3.x中Jakarta包无法引入的问题

    springboot3.x中Jakarta包无法引入的问题

    最近想将一些项目升级到springboot3.x和java17的时候,发现项目依赖中有Jakarta的包,但是代码标红提示没有相关的类,本文就来介绍一下解决方法,感兴趣的可以了解一下
    2024-02-02
  • 一文秒懂springboot druid 配置

    一文秒懂springboot druid 配置

    Druid是阿里巴巴开发的一个连接池,他提供了一个高效、功能强大、可扩展性好的数据库连接池,区别于hikari,今天通过本文给大家分享springboot druid 配置教程,需要的朋友参考下吧
    2021-08-08
  • Java模拟栈和队列数据结构的基本示例讲解

    Java模拟栈和队列数据结构的基本示例讲解

    这篇文章主要介绍了Java模拟栈和队列数据结构的基本示例,栈的后进先出和队列的先进先出是数据结构中最基础的知识,本文则又对Java实现栈和队列结构的方法进行了细分,需要的朋友可以参考下
    2016-04-04
  • Java 批量文件压缩导出并下载到本地示例代码

    Java 批量文件压缩导出并下载到本地示例代码

    这篇文章主要介绍了Java 批量文件压缩导出并下载到本地示例代码,实现思路首先要把zip流写入到http响应输出流中,再把excel的流写入zip流中,具体示例代码,大家通过本文学习吧
    2017-12-12
  • SpringMVC 传日期参数到后台的实例讲解

    SpringMVC 传日期参数到后台的实例讲解

    下面小编就为大家分享一篇SpringMVC 传日期参数到后台的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12

最新评论