5.SpringBoot学习(五)——Spring Boot Profile用法

本文详细介绍了Spring Boot Profile的用法,包括其概念、特点、激活方式和测试结果。通过示例代码展示了如何在dev和prod环境下使用Profile,并分析了Profile在Spring Boot中生效的原理。
摘要由CSDN通过智能技术生成

1.简介

1.1 概述

Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments. Any @Component, @Configuration or @ConfigurationProperties can be marked with @Profile to limit when it is loaded

Spring Profiles 提供了一种隔离应用程序配置部分并使之仅在某些环境中可用的方法。任何 @Component,@ Configuration 或 @ConfigurationProperties 都可以用 @Profile 标记来限制它的加载。

1.2 特点

  1. 可在 xml 中使用;
  2. 可以修饰类、注解、方法;
  3. 可以通过 命令行、系统属性、启动变量、配置文件 等方式激活;

2.环境

  1. JDK 1.8.0_201
  2. Spring Boot 2.2.0.RELEASE
  3. 构建工具(apache maven 3.6.3)
  4. 开发工具(IntelliJ IDEA )

3.代码

3.1 代码说明

提供了 dev、prod 两套环境的配置和代码,测试激活不同的 profile,功能是否如预期

3.2 代码结构

image-20200712213800400

3.3 maven 依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

3.4 配置文件

application.properties

spring.profiles.active=dev

application-dev.properties

spring.application.name=spring-boot-profile
server.port=8080

user.age=20

application-prod.properties

spring.application.name=spring-boot-profile
server.port=9090

user.age=30

3.5 java代码

UserModel.java

public class UserModel {
   

    private String name;

    @Value("${user.age}")
    private Integer age;

    public UserModel(String name, Integer age) {
   
        this.name = name;
        this.age = age;
    }

    public UserModel() {
   
    }

    public String getName() {
   
        return name;
    }

    public void setName(String name) {
   
        this.name = name;
    }

    public Integer getAge() {
   
        return age;
    }

    public void setAge(Integer age) {
   
        this.age = age;
    }

    @Override
    public String toString() {
   
        return "UserModel{name='" + name + '\'' + ", age='" + age + '\'' + '}';
    }
}

DevConfig.java

@Profile("dev")
@Configuration
public class DevConfig {
   

    @Bean
    public UserModel userModel() {
   
        UserModel userModel = new UserModel();
        userModel.setName("zhangsan");
        return userModel
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值