为不同的环境设置配置文件
来看项目结构图:
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")
来指定默认的情况。