初次使用SSH时发现很多朋友在使用
获取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了。
继承接口代码:
注册对象,因为SpringFactory继承了ApplicationContextAware接口,我们在applicationContext.xml中注册该类:
在web.config中初始化Spring容器Ioc:
然后就可以随心所欲的使用SpringFactory中的getObject方法了:
这样就不会再每次去获得对象时去new IOC对象了:
你们也可以自己去断点ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");这段代码,用的时间不是一般的长……^_^.
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");这段代码,用的时间不是一般的长……^_^.