spring 3.0使用PropertyPlaceholderConfigurer
自定义的话,需要继承PropertyPlaceholderConfigurer并重写
protected String resolvePlaceholder(String placeholder, Properties props) {
return props.getProperty(placeholder);
}
spring 3.1(以及之后???)使用PropertySourcesPlaceholderConfigurer
(因为它能够基于Spring Environment及其属性源来解析占位符)
重写参考MyPropConfig
public class MyPropConfig extends PropertySourcesPlaceholderConfigurer{
private MutablePropertySources propertySources;
private PropertySources appliedPropertySources;
private Environment environment;
public void setEnvironment(Environment environment) {
this.environment = environment;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
if (this.propertySources == null) {
this.propertySources = new MutablePropertySources();
if (this.environment != null) {
this.propertySources.addLast(
new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
@Override
public String getProperty(String key) {
return this.source.getProperty(key);
}
}
);
}
try {
PropertySource<?> localPropertySource =
new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
if (this.localOverride) {
this.propertySources.addFirst(localPropertySource);
}
else {
this.propertySources.addLast(localPropertySource);
}
//自定义
PropertySource<?> source = new PropertySource<String>("self") {
@Override
public Object getProperty(String name) {
if(name.equals("jasmine.css")){
return "aa";
}
return null;
}
};
this.propertySources.addLast(source);
}
catch (IOException ex) {
throw new BeanInitializationException("Could not load properties", ex);
}
}
processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
this.appliedPropertySources = this.propertySources;
}
@Override
public PropertySources getAppliedPropertySources() throws IllegalStateException {
Assert.state(this.appliedPropertySources != null, "PropertySources have not get been applied");
return this.appliedPropertySources;
}
}