spring配置文件加载properties文件
时间: 2023-11-29 08:06:04 浏览: 31
好的,关于spring配置文件加载properties文件,可以使用以下几种方式:
1. 使用PropertyPlaceholderConfigurer属性占位符
可以在配置文件中使用${}占位符来引用属性值,同时需要在配置文件中引入对应的*.properties文件。在Spring容器启动时,会通过PropertyPlaceholderConfigurer将properties配置文件中的键值对装载到Spring的环境变量中,供${}占位符使用。
例如:
```
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/config/app.properties</value>
</list>
</property>
</bean>
<bean id="user" class="com.example.User">
<property name="name" value="${user.name}"/>
<property name="age" value="${user.age}"/>
</bean>
```
在上面的例子中,将classpath:/config/app.properties中的键值对装载到Spring的环境变量中,供${}占位符使用。
2. 使用util命名空间的PropertiesFactoryBean
可以在Spring配置文件中使用util命名空间的PropertiesFactoryBean来装载properties文件中的属性,并且使用${}占位符引用这些属性值。
例如:
```
<util:properties id="appConfig" location="classpath:/config/app.properties"/>
<bean id="user" class="com.example.User">
<property name="name" value="${user.name}" />
<property name="age" value="${user.age}" />
</bean>
```
在上面的例子中,通过util:properties装载classpath:/config/app.properties中的属性。在User bean中使用${}占位符引用属性值。
希望这些方法能够帮到您!