扩展Spring中ClassPathXmlApplicationContext的initPropertySource()方法

initPropertySource()方法分析

Spring的强大之处不仅仅在于它为Java开发者提供了极大便利,而且在于它的开放式架构,使得用户可以拥有最大扩展Spring的能力。其中,initPropertySources()方法就是一个例子。

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException{
	super(parent);
	setConfigLocationins(configurations);
	if(refresh){
		refresh();
	}
}

在Spring的ClassPathXmlApplication中,有一个非常重要的方法refresh(),refresh()方法包含了几乎ApplicationContext的所有功能。而refresh()的第一个方法prepareRefresh()是用来准备刷新Spring的上下文环境。

protected void prepareRefresh(){
	initPropertySources();
}

可以看到prepareRefresh()中的initPropertySources()方法并没有任何参数,而如果进入initPropertySources()方法内部,也会发现该方法是空的,没有任何逻辑。
Spring之所这样设计,就是为了让用户根据自己的需要,可以重写initPropertySources()方法,并在方法中进行个性化的属性处理以及设置。

举例

假设工程中需要用到 “VAR” 这个设置是从系统环境变量中取得的,如果用户没有设置这个参数,工程可能不会工作。这个时候,就可以通过扩展initPropertySouces()方法来解决这个问题。

public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext{	
	protected void initPropertySources(){
		//添加验证要求
		getEnvironment().getRequiredProperties("VAR");
	}
}

通过自定义继承自ClassPathXmlApplicationContext的 MyClassPathXmlApplicationContext,并重写initPropertySources()方法,在方法中添加了我们的个性化需求。这样,在验证的时候,程序走到getEnvironment().getRequiredProperties(“VAR”),如果系统没有检测到对应的VAR的环境变量,就会抛出异常。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值