如何在服务器启动的时候自动装在spring容器(例如applicationContext.xml)

9 篇文章 0 订阅

如果要在服务器启动时自动加载spring容器的话,那可定要在web.xml中配置。那么如何配置呢?请看下面代码

第一种:

没有任何的参数,直接通过监听器加载spring容器,这时候默认的读取路径是读取WEB-INF/applicationContext.xml,也就是说spring容器的配置文件只能有一个且名字必须为applicationContext.xml

 

<!-- 通过这个监听器来自动对spring的ApplicationContext进行加载 -->
<listener>

	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 第二种:

 

手动指定参数,改变默认的读取路径,允许多文件读取构成spring容器,像下面这样的话applicationContext1.xml,applicationContext2.xml都能被读进去。

<context-param>
	
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationContext*.xml</param-value>
	
</context-param>

<!-- 通过这个监听器来自动对spring的ApplicationContext进行加载 -->
<listener>

	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

 

那么服务器端怎么使用spring容器呢,如果是Action的话,只需要在Action上定义好与spring容器中bean的id相同的属性,action就会自动装配。如果是Servlet的话,那该怎么做呢?请看如下代码:

private ApplicationContext context;


//spring与Servlet整合的时候,因为Servlet和Filter不能进行自动装配,因此要用Servlet的init()的方法进行手动的赋值
	@SuppressWarnings("unchecked")
	@Override
	public  void init() throws ServletException 
	{
		//hibernateTemplate对象还是从spring容器中获取因为服务器与数据库的连接一个
		context=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		ht=(HibernateTemplate)context.getBean("ht");
		
		hibernateTrans=(UserDaoInterface)context.getBean("hibernateTrans");
		
	};

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值