Java框架篇_05 SpringBoot整合读取配置文件


使用@Value注解读取配置文件

在Spring Boot中,配置文件有两种:

  • application.properties
  • application.yml

或者是

  • bootstrap.properties
  • bootstrap.yml

配置文件在resources目录下,
application.properties配置文件写法:

student.name=Forward
student.age=21

application.yml配置文件写法:

student:
  name: Forward
  age: 21

相比较来说,properties文件比较冗余,yml格式更精简,所以更推荐yml格式。

那么如何读取配置文件呢?可以使用@Value注解:

@RestController
public class StudentService {

    @Value("${student.name}")
    private String name;

    @Value("${student.age}")
    private Integer age;

    @RequestMapping("/getUser")
    public String getUser() {
        return name + ":" + age;
    }
}

bootstrap.yml与 application.yml的配置文件有什么区别呢?

bootstrap.yml先加载,application.yml后加载。bootstrap.yml 用于应用程序上下文的引导阶段。bootstrap.yml 由父Spring ApplicationContext加载。

bootstrap.yml 和 application.yml 都可以用来配置参数。
bootstrap.yml 用来程序引导时执行,应用于更加早期配置信息读取。可以理解成系统级别的一些参数配置,这些参数一般是不会变动的。一旦bootStrap.yml 被加载,则内容不会被覆盖。

application.yml 可以用来定义应用级别的, 应用程序特有配置信息,可以用来配置后续各个模块中需使用的公共参数等。

Properties转yml格式

Properties在线转换yml格式网址:https://www.toyaml.com/index.html

@ConfigurationProperties注解

上面是使用@Value注解,每一个属性都要加上该注解,依旧是冗余。所以Spring Boot提供了@ConfigurationProperties注解,它是加在实体类上的,将配置文件信息自动注入到类中。

yml配置文件:

student:
  name: Forward
  age: 21
  address: 辽宁省沈阳市

使用@ConfigurationProperties注解注入配置文件信息到实体类中,需要用到getter、setter方法,还需要将实体类加入IOC管理,所以需要加如下的注解:

@Component
@ConfigurationProperties(prefix = "student")
@Getter
@Setter
@ToString
public class Student {
    private String name;
    private Integer age;
    private String address;
}

这次只需要注入对象即可

@RestController
public class StudentService {
    @Autowired
    private Student student;

    @RequestMapping
    public String getStudent(){
        return student.toString();
    }
}

配置文件占位符用法

在SpringBoot的配置文件中,我们可以使用SpringBoot提供的的一些随机数${app.name:默认值} 来制定找不到属性时的默认值

${random.value}
${random.int}
${random.long}
${random.int(10)}
${random.int[1024,65536]}

比如yml配置文件中的age:

student:
  name: Forward
  age: ${random.int(10)}
  address: 辽宁省沈阳市

整合多环境不同配置文件

SpringBoot默认读取的配置文件名称是application,我们还可以添加其它配置文件,命名满足application-名称即可。
比如:

application-dev.yml:开发环境
application-test.yml:测试环境
application-prd.yml:生产环境

那么如何是SpringBoot读取对应环境下的配置文件呢呢?
只需要在appliction的配置文件中做如下配置即可

spring:
  profiles:
    active: dev # 配置文件名称后缀

修改端口与上下文路径

最后谈谈Spring Boot如何修改Tomcat容器的端口号,如何加上上下文路径。
只需要在配置文件做如下的配置:

server:
  port: 8081 # 配置端口号
  servlet:
    context-path: /test # 配置访问路径

像这样配置,我访问的时候就应该这么访问 localhost:8081/test/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值