spring之自定义解析配置类

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;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值