Spring boot Properties文件读取

本文介绍如何在SpringBoot中通过@ConfigurationProperties注解读取配置文件(test.properties)中的属性,并将其映射到Java Bean中。文章提供了两个配置类的示例,展示了不同方式下属性文件的读取与注入。

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

[b]Spring boot Properties文件读取[/b]


@Configuration // 相当于定义XML文件
@ConfigurationProperties(prefix = "Test",locations = "classpath:test.properties")
// prefix,所需字段以什么开头的
// locations,没有时默认读取application.properties文件,设置后读取相应的properties文件
public class TestConfig {
private String id; // 需要它的set方法才可以进行Properties文件内容的引入
private String name;

@Bean(name = "testBean") // 相当于XML里配置bean,没有名字时为bean的名字(首写字母小写)
public TestBean testBean() {

TestBean client = new TestBean(id, name);
return client;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getName() {
return name;
}

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



@ConfigurationProperties也可以放在方法外面
@Configuration // 相当于定义XML文件
public class TestBean3Config {
@Bean(name = "testBean3") // 相当于XML里配置bean
@ConfigurationProperties(prefix = "Test", locations = "classpath:test.properties") // 所需字段以什么开头的
public TestBean2 testBean2() {
return new TestBean2();
}
}



@Configuration // 相当于定义XML文件
//@ImportResource("classpath:dubbo-provider.xml")//包含xml文件进来
public class TestBean4Config {

@Value("${Test.}") //这种方式只能使用application.properties,不能放在别的地方
private String id;
@Value("${Test.name}")
private String name;

@Bean(name = "testBean4") // 相当于XML里配置bean

public TestBean testBean4() {
System.out.println("TestBean4Config id == " + id);
System.out.println("TestBean4Config name == " + name);
return new TestBean(id, name);
}
}



参考原文:[url]http://www.cnblogs.com/softidea/p/5683522.html[/url]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值