第一種使用注解:用 @Value("${xxxx}")注解
1. 用法:
從配置properties文件中讀取init.password 的值。
@Value("${init.password}") private String initPwd;
2. 在spring的配置文件中加載配置文件dbconfig.properties :
<!-- 加載配置文件 -->
<bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="fileEncoding" value="UTF-8"/>
<property name="locations">
<list>
<value>classpath:dbconfig.properties</value>
</list>
</property>
</bean>
或者這樣加載:
<context:property-placeholder location="classpath:app.properties" ignore-unresolvable="true" />
同個模塊中如果出現多個context:property-placeholder ,location properties文件后,運行時出現Could not resolve placeholder 'key' in string value${key}。原因是在加載第一個context:property-placeholder時會掃描所有的bean,而有的bean里面出現第二個 context:property-placeholder引入的properties的占位符${key},此時還沒有加載第二個property-placeholder,所以解析不了${key}。解決辦法一,可以將通過模塊的多個property-placeholder合並為一個,將初始化放在一起。方法二,添加ignore-unresolvable="true",這樣可以在加載第一個property-placeholder時出現解析不了的占位符進行忽略掉。
或者這樣加載:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
<property name="location">
<value>dbconfig.properties</value>
</property>
</bean>
3. dbconfig.properties 文件:
#MD5 password.algorithmName=md5 password.hashIterations=2 #initpwd init.password=admin
第二種使用Properties類
public class PropertiesUtil { private static final Logger logger = LoggerFactory.getLogger(PropertiesUtil.class); private static Properties properties; private static String fileName = "/app.properties"; static { properties = new Properties(); try { properties.load(PropertiesUtil.class.getResourceAsStream(fileName)); } catch (IOException e) { logger.error("加載配置文件失敗", e); } } public static Properties getProperties() { return properties; } public static String getProp(String propName) { return properties.getProperty(propName); } }
使用:PropertiesUtil.getProp("xxx"); //其中xxx為properties配置文件的屬性