非spring托管对象如何获取到spring托管对象

来源:互联网 发布:淘宝西服定制 编辑:程序博客网 时间:2024/05/16 08:23

非spring托管对象要获取到spring托管对象,主要是对ApplicationContext的获取

 

总共可以分为以下四种方式获取ApplicationContext:

,通过spring配置文件applicationContext.xml初始化

import org.springframework.context.ApplicationContext;import org.springframework.context.support.FileSystemXmlApplicationContext;public class SpringUtil{private static ApplicationContext applicationContext = null;public static ApplicationContext getApplicationContext() {if(applicationContext == null){applicationContext = new FileSystemXmlApplicationContext("applicationContext.xml");}return applicationContext;}}

当然这里面的applicationContext.xml是全文件路径,这也是这种方式不是很灵活的原因之一,

另一个是通过此种方式,系统保存了2个ApplicationContext对象(静态类型,如果是非静态,那么每次调用该方法时都会new一个该对象,效率应该会更差)。

,通过spring工具类获取

import org.springframework.context.ApplicationContext;import org.springframework.web.context.support.WebApplicationContextUtils;public class SpringUtil{private static ApplicationContext applicationContext = null;public ApplicationContext getApplicationContext(){if(applicationContext == null){applicationContext = WebApplicationContextUtils.getWebApplicationContext(ServletContext sc);}return applicationContext;}}

这里由于不知道ServletContext如何获取,所以没有用这种方法

工具类获取失败时返回null

applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

也可以使用此方法,工具类获取失败时报异常
 

,通过继承抽象类ApplicationObjectSupport

public class SpringUtil extends ApplicationObjectSupport {private ApplicationContext applicationContext = super.getApplicationContext();public ApplicationContext getAC(){return applicationContext;}}

在ApplicationObjectSupport中get/setApplicationContext都为final类型

四,通过实现ApplicationContextAware接口

在spring初始化时,会通过该接口实现的setApplicationComtext方法将ApplicationContext对象注入到该类中,具体见下面

 

我的解决方式选择的第四种:

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class SpringUtil implements ApplicationContextAware {private static ApplicationContext applicationContext;public static ApplicationContext getApplicationContext() {return applicationContext;}public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {SpringUtil.applicationContext = applicationContext;}}

配置文件为:

<?xml version="1.0"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="applicationContext" class="com.test.util.SpringUtil"/></beans>

最后将该类的配置文件加到applicationContext.xml中:

<import resource="com/test/springconfig/springutil.xml" /> 


通过如下方法便能获取到所有由spring管理的对象了:

private InfoBO infoBOProxy = (InfoBO) SpringUtil.getApplicationContext().getBean("infoBOProxy");

对于spring的了解比较肤浅,有什么错误也希望各位指点

原创粉丝点击