SpringBoot自定义配置文件区分环境配置
自定义的配置文件也要区分环境
1.设置自定义的配置文件
1 2 3 4
| ##只写一个属性方便测试
my.name=dev
|
1 2 3
| ##只写一个属性方便测试 my.name=test
|
2.编写配置文件实体类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
public class MyConfig { private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public MyConfig(String name) { this.name = name; } }
|
2.编写配置文件接口
方便spring注入,也可以增加业务逻辑
1 2 3 4 5 6 7
|
public interface IMyConfig { MyConfig getMyConfig(); }
|
3.编写不同环境下对应的实体类
test
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
@Component("myConfig") @Configuration
@PropertySource("classpath:my-test.properties")
@ConfigurationProperties(prefix="my")
@Profile("test") public class MyConfigTest implements IMyConfig{ private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; } @Override public MyConfig getMyConfig() { return new MyConfig(this.name); } }
|
dev
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
@Component("myConfig") @Configuration
@PropertySource("classpath:my-dev.properties")
@ConfigurationProperties(prefix="my")
@Profile("dev") public class MyConfigDev implements IMyConfig{ private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override public MyConfig getMyConfig() { return new MyConfig(this.name); } }
|
4.编写测试类验证
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| @RunWith(SpringRunner.class) @SpringBootTest public class ApplicationTests { @Autowired IMyConfig myConfig; @Test public void testMyConfig() { MyConfig myConfig = this.myConfig.getMyConfig(); System.out.println(myConfig.getName()); }
}
|