Spring读取自定义properties配置文件

本文以PropertyPlaceholderConfigurer为例,介绍了如何在Spring中读取自定义的config.properties配置文件。涉及四个关键文件:config.properties、HelloWorldBean.java、config.xml及Controller。详细解释了每个文件的作用,并提供了Controller中调用配置的代码片段,实现配置文件的读取和应用。

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

这里只提供一种可实现方法,其它方法不讨论。

我们使用PropertyPlaceholderConfigurer方法为例,涉及四个文件:

1:properties文件,这里是config.properties,放置在properties文件常放置的地方,即src/main/resources目录下

2:一个存放properties配置文件属性的Bean,这里是HelloWorldBean.java

3:配置文件,这里是config.xml,由于我们要使用ClassPathXmlApplicationContext读取这个配置文件,因此这个文件要放置在WEB-INF/classes目录下才会被ClassPathXmlApplicationContext找到

4:读取配置的Controller

下面对每个文件的具体内容做详细解释:

config.properties

HelloWorldBean.hello=Hello Properties!!!

其中前面的HelloWorldBean.bean可以随便取名,不过会和后面的配置一一对应,我们在后面会看到,Hello Properties!!!是属性值

HelloWorldBean.java

package com.yunzu.movierecommend;

public class HelloWorldBean {
	private String helloworld;

	/**
	 * @return the helloworld
	 */
	public String getHelloworld() {
		return helloworld;
	}

	/**
	 * @param helloworld the helloworld to set
	 */
	public void setHelloworld(String helloworld) {
		this.helloworld = helloworld;
	}	
}
这里的类名HelloWorldBean和成员变量helloworld在下面的config.xml中都有对应设置
config.xml

<?xml version= "1.0" encoding= "UTF-8"?>
<!DOCTYPE beans PUBLIC  "-//SPRING//DTD BEAN//EN"  "http://www.springframework.org/dtd/spring-beans.dtd">
<beans> 
	<bean id="propertyConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:config.properties" />
	</bean>
	
	<bean id="HelloWorld" class="com.yunzu.movierecommend.HelloWorldBean">
		<property name="helloworld"  value= "${HelloWorldBean.hello}"  /> 
	</bean>
</beans>

注意上面的配置中:

<property name="location" value="classpath:config.properties" />
指明properties文件的名称

	<bean id="HelloWorld" class="com.yunzu.movierecommend.HelloWorldBean">
		<property name="helloworld"  value= "${HelloWorldBean.hello}"  /> 
	</bean>

id是自己取的一个名字,什么都是可以的,class必须是对应的Bean类名,property的name必须对应Bean中对应定义的成员变量,这里是helloworld,value对应properties文件对应的定义

Controller中对应的调用代码

    private String HELLO_WORLD = "aaaasdf___aaasf";


	@PostConstruct
	public void init()
	{
		ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");
		HelloWorldBean hwb = (HelloWorldBean)context.getBean("HelloWorld");
		HELLO_WORLD = hwb.getHelloworld();
		System.out.println( "HELLO_WORLD is: " + HELLO_WORLD );		
	}

其中:

		ApplicationContext context = new ClassPathXmlApplicationContext("config.xml");

上面代码打开WEB-INF/classes目录下的config.xml文件

HelloWorldBean hwb = (HelloWorldBean)context.getBean("HelloWorld");

上面的代码获得id为HelloWorld的Bean,properties文件中的值会设置到Bean中,可以通过get方法获得

有以上这些代码,就可以测试了


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值