SpringBoot 中使用 @profile 动态切换环境配置
2018-12-03 本文已影响0人
289601176aa7
MyPojo.java
import com.xiaoleilu.hutool.json.JSONUtil;
/**
* @ClassName MyPojo
*/
public class MyPojo {
private String name;
private String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return JSONUtil.toJsonStr(this);
}
}
AcmePropConfig .java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
/**
* Profile: Spring为我们提供的可以根据当前环境,动态的激活和切换一系列组件的功能;
*
* @Profile:指定组件在哪个环境的情况下才能被注册到容器中,不指定,任何环境下都能注册这个组件
* 1)加了环境标识的bean,只有这个环境被激活的时候才能注册到容器中。默认是default环境
* 2)写在配置类上,只有是指定的环境的时候,整个配置类里面的所有配置才能开始生效
* 3)没有标注环境标识的bean在,任何环境下都是加载的;
*/
@Configuration
public class AcmePropConfig {
@Bean("myPojo")
@Profile("dev")
public MyPojo getMyPojo() {
MyPojo pojo = new MyPojo();
pojo.setName("dev");
pojo.setDescription("i am dev");
return pojo;
}
@Bean("myPojo")
@Profile("test")
public MyPojo MyPojo_test() {
MyPojo pojo = new MyPojo();
pojo.setName("test");
pojo.setDescription("i am test");
return pojo;
}
}
配置
在application.yaml 中配置使用的环境
spring:
profiles:
active: test
测试类:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MvcApplicationTests {
@Test
public void contextLoads() {
}
@Autowired
private MyPojo myPojo;
@Test
public void test() {
System.out.println(myPojo.toString());
}
}