1、Profile功能
为了方便多环境适配,springboot简化了profile功能。
1、application-profile功能
● 默认配置文件 application.yaml;任何时候都会加载
● 指定环境配置文件 application-XX.yaml
● 激活指定环境
○ 在默认的配置文件中激活:spring.profile.active=XX
○ cmd命令行激活:java -jar xxx.jar --spring.profiles.active=prod --person.name=haha
■ 修改配置文件的任意值,cmd命令行优先
● 默认配置与环境配置同时生效
● 同名配置项,profile配置优先,并不是默认配置
使用:在不同的环境中调用不同的类
①、首先创建我们的bean:
@Component
public interface animal {
String getName();
int getAge();
}
创建两类实现我们的接口:
@Profile(value = "fish")
@Data
@Component
@ConfigurationProperties("cat")
public class Cat implements animal {
private String name;
private int age;
}
@Profile(value = "meat")
@Data
@Component
@ConfigurationProperties("dog")
public class Dog implements animal {
private String name;
private int age;
}
创建三个配置文件,其中第一个为默认配置文件

在我们的默认配置文件中指向我们的meat
spring.profiles.active=meat
因为我们默认配置文件中profile指向的是fish,而我们的cat类中的profile的value是fish,所以我们的就会输出
class com.atguigu.boot.bean.Cat
@Controller
public class animalController {
@Autowired
animal animal;
@ResponseBody
@GetMapping("/animal")
public String test01(){
return animal.getClass().toString();
}
}
②、我们也可以对我们类中的方法进行使用;即在不同的环境下该类使用的方法不同。
③、使用profile分组:
spring.profiles.group.production[0]=proddb
spring.profiles.group.production[1]=prodmq
使用:--spring.profiles.active=production 激活,之后我们将会使用的是probdb和prodmq环境
本文介绍了Spring Boot如何简化profile配置,通过激活不同环境实现类的切换,以及如何在不同配置文件和环境间设置优先级。还展示了如何根据profile分组和使用不同的类实例。
1632

被折叠的 条评论
为什么被折叠?



