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编程中finally语句的基本使用方法

    讲解Java编程中finally语句的基本使用方法

    这篇文章主要介绍了讲解Java编程中finally语句的基本使用方法,finally在异常处理中的使用时Java入门学习中的基础知识,需要的朋友可以参考下
    2015-11-11
  • MybatisPlusException:Failed to process,Error SQL异常报错的解决办法

    MybatisPlusException:Failed to process,Error SQL异常报错的解决办法

    这篇文章主要给大家介绍了关于MybatisPlusException:Failed to process,Error SQL异常报错的解决办法,文中通过实例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2023-03-03
  • Mybatis基于xml配置实现单表的增删改查功能

    Mybatis基于xml配置实现单表的增删改查功能

    这篇文章主要介绍了Mybatis基于xml配置实现单表的增删改查,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-04-04
  • 如何解决@NotBlank不生效的问题

    如何解决@NotBlank不生效的问题

    这篇文章主要介绍了如何解决@NotBlank不生效的问题,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06
  • 深入了解Spring中的FactoryBean

    深入了解Spring中的FactoryBean

    这篇文章主要介绍了深入了解Spring中的FactoryBean,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • Java中流的有关知识点详解

    Java中流的有关知识点详解

    今天小编就为大家分享一篇关于Java中流的有关知识点详解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-01-01
  • Java后台通过Collections获取list集合中最大数,最小数代码

    Java后台通过Collections获取list集合中最大数,最小数代码

    这篇文章主要介绍了Java后台通过Collections获取list集合中最大数,最小数代码,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-08-08
  • IntelliJ IDEA创建maven多模块项目(图文教程)

    IntelliJ IDEA创建maven多模块项目(图文教程)

    这篇文章主要介绍了IntelliJ IDEA创建maven多模块项目(图文教程),非常具有实用价值,需要的朋友可以参考下
    2017-09-09
  • java+Okhttp3调用接口的实例

    java+Okhttp3调用接口的实例

    这篇文章主要介绍了java+Okhttp3调用接口的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • java实现分页显示效果

    java实现分页显示效果

    这篇文章主要为大家详细介绍了java实现页显示效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-08-08

最新评论