一、不通过注解
1.Spring 配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
2.通过ClassPathResource类 加载 配置文件
private static Properties props = new Properties();
static {
try {
props.load(new ClassPathResource("config.properties").getInputStream());
} catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(-1);
} catch (IOException e) {
System.exit(-1);
}
}
public static String getKeyValue(String key) {
return props.getProperty(key);
}
二、通过注解(Spring 4支持)
1.spring 配置
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
2.注解获取
@Value("#{propertyConfigurer['jdbc.jdbcUrl']}")
private String jdbcUrl;