在业务开发中,配置配置项是基本能力。本篇总结下SpringBoot中常用的配置项使用方法。
1,最基础的直接使用
在配置文件application.yml中写好配置。
在代码中直接使用
@RestController public class HelloController { @Value("${spring101.name}") private String name; @Value("${spring101.age}") private int age; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String sayHello(){ String result = "my name is " + name + "and age is" + age; return result; } }
测试:
很简单,能多说一句就是,在配置时是弱类型的,我们并没有定义string还是int。但是在代码里使用的时候,如果是int类型,spring是能够完成自动转换的。
2,在配置文件中使用配置项
我不想在代码里对多个配置项进行组装,可以在配置文件中对配置项进行操作,组合成一个新的配置项,供代码使用。
配置文件改成这样:
spring101: name: uncley age: 20 content: "content name is ${spring101.name} and age is ${spring101.age}"
代码:
@RestController public class HelloController { @Value("${spring101.name}") private String name; @Value("${spring101.age}") private int age; @Value("${spring101.content}") private String content; @RequestMapping(value = "/hello", method = RequestMethod.GET) public String sayHello(){ // String result = "my name is " + name + ", and age is" + age; return content; } }
测试:
总结:在配置文件中可以通过${}直接使用配置文件中定义好的配置项。
3,配置项转换为bean
如果配置项很多,每次使用时,需要一次次的写@Value也是有点麻烦。这时可以将配置项转换成一个bean,以后通过这个bean直接get就方便多了。
首先定义一个bean
@Component @ConfigurationProperties(prefix = "spring101") @Data public class Uncle { private String name; private int age; private String content; }
@Component方便后面自动注入使用。
@ConfigurationProperties是关键,prefix指定配置项的前缀
@Data是lombok的注解,我前面的文章有过介绍,用来简化代码而已,非必须。
然后改下controller使用,增加如下代码
@Autowired private Uncle uncle; @RequestMapping(value = "/helloUncle", method = RequestMethod.GET) public String sayHelloUncle(){ return uncle.toString(); }
测试:
ok,配置项全都通过bean拿到了。
4,多环境切换
再有一个,配置项使用经常遇到的场景是测试环境和生产环境需要切换参数。
这个可以通过配置profile搞定。
application.yml配置文件做如下修改:
spring: profiles: active: prod spring101: name: uncley content: "content name is ${spring101.name} and age is ${spring101.age}" --- spring: profiles: test spring101: age: 20 --- spring: profiles: prod spring101: age: 40
spring.profiles.active执行那个环境生效。
---用来区隔环境
spring.profiles用来表示当前环境名
我现在是把name和content方外外面,作为公共部分使用。
在生产和测试环境中配置了不同的age
通过修改spring.profiles.active的值达到区分环境的目的。
测试一下
多说一句,如果已经打好了包,在不同环境部署时,并不需要改下配置文件重新打包。
因为我们使用java -jar xxx.jar --spring.profiles.active=prod
后面加--spring.profiles.active就可以在启动jar包时指定要使用的环境了。