【spring】动态加载配置文件

本文详细介绍了如何在Spring框架中使用ContextLoaderListener来初始化应用程序上下文,并通过配置参数加载多个配置文件,实现了灵活的模块化开发。重点讨论了ContextLoaderListener的实现原理及其实例化过程,包括如何在特定条件下加载额外的Spring配置文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

web.xml

	<context-param>  
	    <param-name>contextConfigLocation</param-name>  
	    <param-value>classpath:config/spring/spring-core.xml</param-value>  
	</context-param>  
  	<listener>
       <span style="white-space:pre">		</span><listener-class>com.myproject.support.ContextLoaderListener</listener-class>
    <span style="white-space:pre">	</span></listener> 

ContextLoaderListener 

public class ContextLoaderListener extends org.springframework.web.context.ContextLoaderListener {
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void contextInitialized(ServletContextEvent event) {
		if( "true".equals(PropertiesUtil.get("otherFlag")) ){//当<span style="font-family: Arial, Helvetica, sans-serif;">otherFlag为true时加载spring-other.xml文件</span>
			ServletContext servletContext = event.getServletContext();
			try {
				Field contextField = servletContext.getClass().getDeclaredField("context");
				contextField.setAccessible(true);
				Object context = contextField.get(servletContext);
				Field parametersField = context.getClass().getDeclaredField("parameters");
				parametersField.setAccessible(true);
				Map parameters = (Map)parametersField.get(context);
				parameters.put("contextConfigLocation", parameters.get("contextConfigLocation")+",classpath:config/spring/spring-other.xml");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		super.contextInitialized(event);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值