一.前言
SpringBoot 中配置约定大于配置。
二.获取自定的配置
1.从 application.properties中获取
获取前缀为 config3 的配置文件,自动赋值
application.properties配置文件:
config3.name=name3
config3.pass=pass3
config3.desc=desc3
实体类,这里ConfigurationProperties(prefix = "config3") 指定了前缀为 config3 的配置
// 配置文件前缀为 web
@ConfigurationProperties(prefix = "config3")
@Data
public class PropertyConfig3 {
private String name;
private String pass;
private String desc;
}
将上述装配好的对象加载到 Spring 容器中
@Service
// 并指明要加载哪个bean
@EnableConfigurationProperties({PropertyConfig3.class})
public class PropertyService3 {
// 这个地方只能使用 @Resource IDEA 才不显示错误
@Resource
private PropertyConfig3 config3;
@PostConstruct
public void init() {
System.out.println("PropertyConfig3:" + config3);
}
}
2.从外部的配置文件中获取
这里需要指定外部配置文件的路径,如果配置文件中有中文,则需要指定 encoding = "utf-8"
// 配置文件前缀为 web
@ConfigurationProperties(prefix = "key")
// 获取外部的配置文件文件,需要指定配置文件的路径
@PropertySource(
value = "classpath:other2.properties",
encoding = "utf-8"
)
@Data
public class PropertyConfig2 {
private String name;
private String pass;
private String desc;
}
3.数据类型的约定
经常我们需要导入比较复杂的数据类型如 List,Map,Date等类型
配置文件
# 简单的字符串
web.name=shaodong
web.pass=123456
[email protected]
#List类型数据
web.hobby[0]=movie电影
web.hobby[1]=music
# Map类型的数据
web.map.11=11
web.map.22=22
# 时间类型的数据
web.date=2018/08/14 16:54:30
实体类
// 配置文件前缀为 web
@ConfigurationProperties(prefix = "web")
// 获取外部的配置文件文件,需要指定配置文件的路径
@PropertySource(
ignoreResourceNotFound = true,
value = "file:/Users/shao/Documents/IdeaProjects/SpringBootProperty/src/main/resources/other1.properties",
encoding = "utf-8"
)
@Component
@Data
public class PropertyConfig1 {
private String name;
private String pass;
private String email;
private List hobby;
private Map map;
private Date date;
}
4.URL 路由可配
配置 URL 的路径
配置文件:
controller.url=/get
Controller代码,注意在路由中并没有写死,可以从配置文件中获取
@RestController
public class PropertyController {
private final PropertyConfig1 config1;
public PropertyController(PropertyConfig1 config1) {
this.config1 = config1;
}
/**
* 从配置文件中获取 URL 路由
*
* @return return
*/
@GetMapping("${controller.url1}")
public PropertyConfig1 get1() {
return config1;
}
}
三. 启用配置文件
1.在配置文件中指定启用的配置文件
SpringBoot 中默认启用的配置文件是application.properties,在这个配置文件中,我们可以指定其他的配置的文件,配置文件的命名格式为:application-XXX.properties,这时我们可以在application.properties使用spring.profiles.active=dev启用
application-dev.properties这个配置文件
2.在单元测试中指定运行加载的配置文件
测试和开发往往使用不同的服务器环境,如果我们使用上述来切换的话,会比较麻烦还容易污染开发环境的数据,这时只需在测试的代码上面添加注解@ActiveProfiles("test")
// 单侧走 test(application-test.properties) 配置文件
// 相当于 spring.profiles.active=test
@ActiveProfiles("test")
@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertyApplicationTests {
@Test
public void contextLoads() {
}
}
3.打完 Jar 包运行指定加载的配置文件
打完包也可以指定运行外部的配置文件
java -jar /Users/shao/Documents/IdeaProjects/client-app-1-0.0.1-SNAPSHOT.jar --spring.config.location=file:///Users/shao/Documents/IdeaProjects/application.properties
未完待续
四.代码路径
https://github.com/shaopro/SpringBootProperty