springboot的application.properties文件中可以定义一些可配置的常量。在程序中我们不需要再重新的读取文件,我们可以直接使用@Value注解读取配置文件中的值。

首先看一下配置文件

springboot 读取配置文件中的变量(通过注解方式)

application.properties中的内容是:

spring.profiles.active=dev


application-dev.properties文件的内容是:

server.port=9991

spring.datasource.url=jdbc:mysql://localhost:3306/xytest
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

democonfig.name=dev
democonfig.age=122

为了读取democonfig.name和democonfig.age的值,我们可以新建一个类,专门读取配置文件。

@Component
public class DemoConfig {
    @Value("${democonfig.name}")
    public String name;

    @Value("${democonfig.age}")
    public int age;

}

这样之后,每次实例化的类中name的值就是dev  age的值就是122。

这样就完成了我们的目的。在类中直接读取了配置文件中的信息。

相关文章:

  • 2022-01-08
  • 2022-01-24
  • 2022-01-09
  • 2022-02-20
  • 2021-12-03
  • 2021-07-18
  • 2021-04-07
  • 2022-02-08
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2023-04-03
  • 2021-09-07
相关资源
相似解决方案