SSH Spring获取Ioc容器管理对象

初次使用SSH时发现很多朋友在使用
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

获取ApplicationContext对象,进过自己测试这段代码适合C/S程序,在javaweb中这样获取ApplicationContext对象是很慢的。每次去getBean(”beanid“)时都会去加载applicationContext.xml",这样效率很低的。
Spring中提供了获取ApplicationContext对象的接口,在org.springframework.context.ApplicationContextAware中我们只需实现ApplicationContextAware接口的setApplicationContext方法,然后Spring的配置文件applicationContext.xml中注册实现ApplicationContextAware接口的类的类,并用静态的ApplicationContext变量把ApplicationContext保存下来,并在web.config中加上以下代码在网站启动时加载到内存中,然后就可以随心所欲的使用静态的ApplicationContext了。

继承接口代码:

package com.ssh.springfactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class SpringFactory implements ApplicationContextAware{

private static ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.context=applicationContext;
}


public static Object getObject(String id) {
Object object = null;
object = context.getBean(id);
return object;
}
}


注册对象,因为SpringFactory继承了ApplicationContextAware接口,我们在applicationContext.xml中注册该类:

<bean id="springfactory" class="com.ssh.springfactory.SpringFactory"></bean>


在web.config中初始化Spring容器Ioc:

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>


然后就可以随心所欲的使用SpringFactory中的getObject方法了:

public static Object getObject(String id) {
Object object = null;
object = context.getBean(id);
return object;
}

这样就不会再每次去获得对象时去new IOC对象了:

ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

你们也可以自己去断点ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");这段代码,用的时间不是一般的长……^_^.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值