Spring Boot Profiles

为不同的环境设置配置文件

来看项目结构图:
这里写图片描述
application.yml:

spring:
  profiles:
    active: dev    # 激活特定环境的profile配置
#    include: usage_message

运行项目以后,会激活application-dev.yml的配置项(杂七杂八的配置:MySQL、Redis、RabbitMQ)。同理,spring.profiles.active=prod则会激活application-prod.yml的配置。

使用profiles加载不同的类
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;

@Profile({"tut1", "hello-world"})  // 可以使用tut1或hello-world激活配置
@Configuration
public class Tut1Config {
    @Bean
    public Queue hello() {
        return new Queue("hello");
    }

    @Profile("receiver")
    @Bean
    public Tut1Receiver receiver() {
        return new Tut1Receiver();
    }

    @Profile("sender")
    @Bean
    public Tut1Sender sender() {
        return new Tut1Sender();
    }
}

为了针对不同的情况加载不同的类,看上面的代码,比如我要激活hello-word Configuration和Tut1Sender类,可以这样:

# 执行spring boot 发送mq消息 
java -jar wechat-shop-admin-app/build/libs/wechat-shop-admin-app-1.0.0-SNAPSHOT.jar --spring.profiles.active=hello-world,sender,dev   

--spring.profiles.active=hello-world,sender,dev,这里我加上了dev选项,因为--spring.profiles.active选项会覆盖application.yml中的spring.profiles.active。通过java -jar去启动,如果指定--spring.profiles.active=hello-world,sender,不加dev的话,application-dev.yml中的配置就不会生效,不信你去试试。

另外profiles这个单词一定要写对,我就写成了profile(少了个s),导致配置不生效,折腾了好久,想哭。

#执行spring boot 接收mq消息 
java -jar wechat-shop-admin-app/build/libs/wechat-shop-admin-app-1.0.0-SNAPSHOT.jar --spring.profiles.active=hello-world,receiver,dev
当特定的profile不存在时,指定默认的方式
    @Profile("!usage_message")
    @Bean
    public CommandLineRunner tutorial() {
        return new RabbitAmqpTutorialsRunner();
    }

usage_message 这个profile不存在时,使用@Profile("!usage_message")来指定默认的情况。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值