读书人

spring工程 使用ApplicationContextAw

发布时间: 2012-09-23 10:28:11 作者: rapoo

spring工程 使用ApplicationContextAware接口获得spring上下文

ApplicationContextAware接口

?

?

import org.springframework.beans.BeansException;

import org.springframework.context.ApplicationContext;

import org.springframework.context.ApplicationContextAware;

import org.springframework.stereotype.Component;

?

@Component

public class My1 implements ApplicationContextAware {

?

public static ApplicationContext act=null;

public void setApplicationContext(ApplicationContext arg0)

throws BeansException {

act=arg0;

}

?

}

?

使用时

My1.act.getBean("object name");

?

其它:

ssh项目中,时常使用WebApplicationContext,来获得spring上下文,如下:

WebApplicationContext wac= null;

wac=WebApplicationContextUtils.getWebApplicationContext(ServletActionContext.getServletContext());

但如果struts2框架未能在调用前加载,则不能正常使用。

// 未成功时,会抛异常

WebApplicationContextUtils.getRequiredWebApplicationContext();

// 为成功时,会返回null

WebApplicationContextUtils.getWebApplicationContext()

读书人网 >编程

热点推荐