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

参考资料

  1. 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环境

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,为了演示如何使用@Profile注解实现多环境配置,我将为您提供一个示例。 @Profile注解可以用于类或方法级别,用于指定哪些bean应该在哪个环境中使用。例如,我们可以创建一个名为"dev"的配置文件来指定开发环境中使用的bean,也可以创建一个名为"prod"的配置文件来指定生产环境中使用的bean。 下面我们来实现一个简单的示例,使用@Profile注解来打印不同的内容。 首先,我们需要创建一个名为"dev"的配置文件和一个名为"prod"的配置文件,分别用于开发环境和生产环境。在这两个配置文件中,我们可以设置不同的输出内容。例如,在"dev"配置文件中,我们可以将以下代码添加到文件末尾: ```properties # 开发环境配置 my.env=dev my.env.content=这是开发环境 ``` 而在"prod"配置文件中,我们可以将以下代码添加到文件末尾: ```properties # 生产环境配置 my.env=prod my.env.content=这是生产环境 ``` 接下来,我们需要在代码中使用@Profile注解来指定使用哪个环境配置。例如,在我们的测试类中,我们可以添加以下代码: ```java @SpringBootTest class MyApplicationTests { @Value("${my.env}") private String env; @Value("${my.env.content}") private String envContent; @Test @Profile("dev") void testDev() { System.out.println("环境是:" + env); System.out.println("内容是:" + envContent); } @Test @Profile("prod") void testProd() { System.out.println("环境是:" + env); System.out.println("内容是:" + envContent); } } ``` 在运行测试方法前,我们需要在启动类中指定使用哪个环境配置。例如,在启动类中,我们可以添加以下代码: ```java @SpringBootApplication public class MyApplication { public static void main(String[] args) { SpringApplication app = new SpringApplication(MyApplication.class); app.setAdditionalProfiles("dev"); // 指定使用dev环境配置 app.run(args); } } ``` 此时,当我们运行MyApplicationTests类中的测试方法时,只有@Profile注解中指定的环境配置会被加载并生效。例如,如果我们指定使用dev环境配置,那么只有testDev()方法中打印的内容会被输出。 希望这个示例可以帮助您使用@Profile注解实现多环境配置
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值