spring boot 使用自定义配置文件读取文件内容

本文介绍如何在Spring Boot项目中使用application.properties和application.yml配置文件,并演示如何通过@Value和@ConfigurationProperties注解来读取配置信息。同时,还介绍了如何自定义配置文件并加载其内容。

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

1.在application.properties中,添加自定义的配置信息

neo.title=纯洁的微笑
neo.description=分享技术,品味生活

同时存在 application.yml 和 application.properties,并且里面配置相同,application.properties 的配置会覆盖 application.yml。

2.读取单个配置项

当需要从配置文件加载单个配置内容时,只需要使用 @Value 属性即可,新建 PropertiesTest 测试类进行测试。

@RunWith(SpringRunner.class)
@SpringBootTest
public class PropertiesTest {
    @Value("${neo.title}")
    private String title;

    @Test
    public void testSingle() {
        Assert.assertEquals(title,"纯洁的微笑");
    }
}
  • @Value("${neo.title}") 会默认读取 application.properties 或者 application.yml 文件中的 neo.title 配置属性值,并赋值给 title。
  • Assert.assertEquals 是判断属性值是否和目标值一致。

3.读取多个配置

@Component
@ConfigurationProperties(prefix="neo")
public class NeoProperties {
    private String title;
    private String description;

    //省略getter settet方法
}
  • @Component 的定义为实例,方便在 Spring Boot 项目中引用;
  • @ConfigurationProperties(prefix="neo"),表示以 neo 开头的属性会自动赋值到对象的属性中,比如,neo.title 会自动赋值到对象属性 title 中。
  • 写单元测试进行验证,使用属性时直接将 NeoProperties 对象注入即可。
@Resource
private NeoProperties properties;

@Test
public void testMore() throws Exception {
    System.out.println("title:"+properties.getTitle());
    System.out.println("description:"+properties.getDescription());
}

4.自定义配置文件

有时候需要自定义配置文件,以便和系统使用的 application.properties 文件区分开,避免混淆。Spring Boot 对这种情况也有很好的支持。

在 resources 目录下创建一个 other.properties 文件,内容如下:

other.title=keep smile
other.blog=www.ityouknow.com
@Component
@ConfigurationProperties(prefix="other")
@PropertySource("classpath:other.properties")
public class OtherProperties {
    private String title;
    private String blog;

    //省略getter settet方法
}

对比上面读取多个配置示例,多了一个注解来指明配置文件地址:@PropertySource("classpath:other.properties"),同样创建一个测试方法,检测是否正确加载了外部配置文件。

@Test
public void testOther() throws Exception {
    System.out.println("title:"+otherProperties.getTitle());
    System.out.println("blog:"+otherProperties.getBlog());
}

如果测试中出现中文乱码,可按照以下方法进行设置:

依次单击 File | Settings | Editor | File Encodings 命令,将 Properties Files (*.properties) 下的 Default encoding for properties files 设置为 UTF-8,勾选 Transparent native-to-ascii conversion 复选框。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值