Spring Boot读取properties配置文件中数据的三种方法

时间:2025-02-13 08:56:05

题记:

      整理一下springboot获取配置文件的笔记!springboot获取配置文件的方式分为三种:

      1,使用@Value获取配置文件内容

       2,使用@ConfigurationProperties获取配置文件内容

       3,使用Environment对象

一、使用@Value获取配置文件内容

:配置文件代码:

=11111
=USA
=Spring
=high
=Hello World

PropertiesConfig1实体:

package ;

import ;
import ;
import ;
import ;
import ;

@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
public class PropertiesConfig1 {

    @Value("${}")
    private String address;

    @Value("${}")
    private String company;

    @Value("${}")
    private String degree;
}

测试类:

/**
     * 注意:如果@Value${}所包含的键名在配置文件中不存在的话,会抛出异常:
     * : Error creating bean with name 'configBeanValue': Injection of autowired dependencies failed; nested exception is : Could not resolve placeholder '' in value "${}"
     */
    @Autowired
    private PropertiesConfig1 propertiesConfig1;
    @GetMapping("/test1")
    @ApiOperation(value = "使用@Value获取配置文件内容")
    public void test1() {
        // PropertiesConfig propertiesConfig = new PropertiesConfig();
        (propertiesConfig1);
    }

二、使用@ConfigurationProperties获取配置文件内容

PropertiesConfig2实体:
package ;

import ;
import ;
import ;
import ;
import ;

/**
 * @Component 表示将该类标识为Bean
 * @ConfigurationProperties(prefix = "demo")用于绑定属性,其中prefix表示所绑定的属性的前缀。
 * @PropertySource(value = "")表示配置文件路径。默认配置文件可以不指定
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@Component
@ConfigurationProperties(prefix = "info")
public class PropertiesConfig2 {
    private String address;

    private String company;

    private String degree;
}

测试类:

在实际项目中,当项目需要注入的变量值很多时,上述所述的两种方法工作量会变得比较大,这时候我们通常使用基于类型安全的配置方式,将properties属性和一个Bean关联在一起,即使用注解@ConfigurationProperties读取配置文件数据。

/**
     * 在实际项目中,当项目需要注入的变量值很多时,上述所述的两种方法工作量会变得比较大,这时候我们通常使用基于类型安全的配置方式,将properties属性和一个Bean关联在一起,即使用注解@ConfigurationProperties读取配置文件数据。
     */
    @Autowired
    private PropertiesConfig2 propertiesConfig2;
    @GetMapping("/test2")
    @ApiOperation(value = "使用@ConfigurationProperties获取配置文件内容")
    public void test2() {
        (propertiesConfig2);
    }

三、使用Environment对象

使用Environment不用创建实体,可直接根据配置文件中需要获取的属性前缀获取。

测试代码

@Autowired
    private Environment environment;
    @GetMapping("/test3")
    @ApiOperation(value = "获取environment")
    public void test3() {
        ((""));
    }