spring-boot 如何加载rsources下面的自定义配置文件

本文介绍了如何在Spring Boot应用中加载resources目录下的自定义配置文件config.properties。首先,创建配置文件并设置属性;然后,创建一个读取配置的类,使用@PropertySource注解指定配置源,并通过@Value注解注入属性值;最后,通过测试类验证配置文件的读取是否成功。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建一个自定义properties文件,如下:

config.msg = hello world!
config.name = "潘浩"


2.写一个读取配置文件的类

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;


@Component
@PropertySource("classpath:config.properties")
/**
 * 在@ConfigurationProperties注释中有两个属性:
prefix:指定配置文件中键名称的前缀(我这里配置文件中所有键名都是以web.开头)
 * @author 潘浩
 */
public class MyConfig {


@Value("${config.msg}")
private String msg;

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


public String getMsg() {
return msg;
}


public String getName() {
return name;
}

}

3.写一个测试类可以测试是否成功读取配置文件中的属性.


/**
 * 测试类
 * 
 * @author 潘浩
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=GlsserviceProviderProjectMgrApplication.class)  // 指定spring-boot的启动类   
public class ControllerTest {

@Autowired
    private MyConfig myConfig;

@Test
public void test_如何获取配置文件中的属性值()
{
System.out.println("test_如何获取配置文件中的属性值: "+myConfig.getMsg());
}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值