[易学SpringBoot]配置项的使用总结

在业务开发中,配置配置项是基本能力。本篇总结下SpringBoot中常用的配置项使用方法。

1,最基础的直接使用

[易学SpringBoot]配置项的使用总结

 

在配置文件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;
 }
}

测试:

[易学SpringBoot]配置项的使用总结

 

很简单,能多说一句就是,在配置时是弱类型的,我们并没有定义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;
 }
}

测试:

[易学SpringBoot]配置项的使用总结

 

总结:在配置文件中可以通过${}直接使用配置文件中定义好的配置项。

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();
}

测试:

[易学SpringBoot]配置项的使用总结

 

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的值达到区分环境的目的。

测试一下

[易学SpringBoot]配置项的使用总结

 

多说一句,如果已经打好了包,在不同环境部署时,并不需要改下配置文件重新打包。

因为我们使用java -jar xxx.jar --spring.profiles.active=prod

后面加--spring.profiles.active就可以在启动jar包时指定要使用的环境了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值