SpringBoot:通过@ConfigurationProperties(prefix = "test")注解读取配置文件

郎家岭伯爵 2021年12月29日 451次浏览

背景

学习过程中需要将账号、密码等类似的数据写入到配置文件中,代码中通过读取配置文件进行赋值。

实现

application.properties文件内容

test.name=langjialing

注:

  • 配置项key值应为小写。

测试类

package com.langjialing.controller;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
//可通过@PropertySource("classpath:user.properties")注解指定properties文件,例如新建一个user.properties文件。
//@PropertySource("classpath:user.properties")
@ConfigurationProperties(prefix = "test")
public class PropertiesTestDemo {

    private static String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

注:

  • private static String name;变量name是需要加static的,但是gettersetter方法是不能加static的。这应该是加载顺序造成的影响,博主水平有限。如有大佬知悉原因可邮件指点下,届时会在博文中说明。

Junit单元测试验证结果

@Test
void propertiesTestDemo(){
    PropertiesTestDemo propertiesTestDemo = new PropertiesTestDemo();
    String s1 = propertiesTestDemo.getName();
    System.out.println(s1);
}

总结

@Component与@ConfigurationProperties(prefix = "test")可实现从配置文件中读取数据并赋值给业务代码使用。

赞助页面示例