Spring的properties配置文件注入

1. 使用PropertiesFactoryBean

配置文件

<bean id="config" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
	<property name="locations">
		<list>
			<value>classpath:app.properties</value>
		</list>
	</property>
	<property name="fileEncoding" value="UTF-8" />
</bean>
<!-- 可以简写成 -->
<util:properties id="config" location="classpath:app.properties"/>

代码

@Value("#{config[host]}")
private String host;

注意

@Value("#{config[host]}")中不能有".",例如server.host,不能正确解析

2. PropertyPlaceholderConfigurer

配置文件

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<array>
			<value>classpath:app.properties</value>
		</array>
	</property>
	<property name="fileEncoding" value="UTF-8"></property>
</bean>
<!-- 可以简写成 -->
<context:property-placeholder location="classpath:app.properties"/>

<context:property-placeholder     
        location="属性文件,多个之间逗号分隔"    
        file-encoding="文件编码"    
        ignore-resource-not-found="是否忽略找不到的属性文件"    
        ignore-unresolvable="是否忽略解析不到的属性,如果不忽略,找不到将抛出异常"    
        properties-ref="本地Properties配置"    
        local-override="是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性,否则相反"    
        system-properties-mode="系统属性模式,默认ENVIRONMENT(表示先找ENVIRONMENT,再找properties-ref/location的),NEVER:表示永远不用ENVIRONMENT的,OVERRIDE类似于ENVIRONMENT"    
        order="顺序"    
        />

代码

@Value("${server.host}")
private String host;

猜你喜欢

转载自blog.csdn.net/hejian708837/article/details/85129257