我想重写java.util.Properties类中的getProperty()方法,请告知。
1. 1.Spring上下文文件
spring-context.xml
<bean id="myproperty" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations" value="classpath:myproperties.properties" />
</bean>
Java类
public class MyClass{
@Autowired
public void setMyproperty(Properties myproperty) {
this.url=myproperty.getProperty("url");
}
}
3.配置文件
myproperties.properties
url=http://stackoverflow.com
仅供参考:我正在从配置文件中提取批次值,我想在从.properties获得值后调用trim(),以避免试图覆盖getProperty()方法的代码冗余。
使用:Spring 4.0
发布于 2018-09-08 18:09:59
扩展spring默认属性占位符(PropertyPlaceholderConfigurer)并捕获它在局部变量中加载的属性。
public class PropertiesUtils extends PropertyPlaceholderConfigurer {
private static Map<String, String> propertiesMap;
private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;
@Override
public void setSystemPropertiesMode(int systemPropertiesMode) {
super.setSystemPropertiesMode(systemPropertiesMode);
springSystemPropertiesMode = systemPropertiesMode;
}
@Override
protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
super.processProperties(beanFactory, props);
propertiesMap = new HashMap<String, String>();
for (Object key : props.keySet()) {
String keyStr = key.toString();
String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
propertiesMap.put(keyStr, valueStr);
}
}
public static String getProperty(String name) {
return propertiesMap.get(name).toString();
}
https://stackoverflow.com/questions/52232472
复制相似问题