Profile环境切换
配置文件可以写多个通过application-xxx.yaml来区别不同的生产环境。
比如
这里创建了三个配置文件,不加后缀的是默认配置环境,项目启动时默认配置文件加载,根据spring.profile.active来选择不同的配置文件激活,默认配置和指定环境的配置文件都生效,如果有同名的配置则指定生产环境生效。
application.yaml
spring:
profiles:
active: dev
# dev环境激活
application-dev.yaml
person:
name: "dev"
application-test.yaml
person:
name: "test"
这里写一个controlller来测试一下
@Controller
public class ProfileController {
@Value("${person.name}")
String name;
@RequestMapping("/hello")
@ResponseBody
public String hello(){
return "hello"+name;
}
}
激活不同的测试环境或者不激活使用默认配置。
这里也可以换一种玩法,创建一个类,使用配置文件绑定对应信息然后返回。
准备一个Person类,注意要加getter和setter否则没法绑定
@Data
@Component
@ConfigurationProperties("person")
public class Person {
String name;
Integer age;
}
application.yaml
person:
name: "默认环境"
age: 20
application-dev.yaml
person:
name: "dev"
age: 18
application-test.yaml
person:
name: "test"
age: 19
Controller
@Controller
public class ProfileController {
@Autowired
Person person;
@RequestMapping("/hello")
@ResponseBody
public Person hello(){
return person;
}
}
Profile条件装配
现在我们想实现根据不同的生产环境接口的实现类也发生改变。
先创建一个接口和两个实现类
通过@Profile注解来实现在不同生产环境下装配不同的类,举个例子我们现在需要在dev环境下装配Boss,test环境下装配Worker。这两个类同时继承了Company接口。
Company
public interface Company {
}
Worker
import com.example.boot2admin.profile.Company;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Data
@Component
@Profile("test")
@ConfigurationProperties("person")
public class Worker implements Company {
private String name;
private Integer age;
}
Boss
import com.example.boot2admin.profile.Company;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
@Data
@Component
@Profile("dev")
@ConfigurationProperties("person")
public class Boss implements Company {
private String name;
private Integer age;
}
配置文件不变,就可以实现不同生产环境的条件装配了。
Profile分组
比如说我们想合并两个配置文件,这个时候我们可以使用分组的方式实现。
application.yaml:这里是将dev和prod两个环境合并成一个环境起名叫product并激活这个环境
spring:
profiles:
active: product
group:
product[0]: dev
product[1]: prod