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");這段代碼,用的時間不是一般的長……^_^.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章