在应用中获取Spring的应用上下文

第一种方法,在servlet中

ServletContext servletContext =this.getServletContext();

WebApplicationContext wac = WebApplicationContextUtils.
                                    getRequiredWebApplicationContext(servletContext);

User user = (User)wac.getBean("user");
 

第二种方法,做一个ApplicationContextAware的Bean,并实现setApplicationContext方法

public class ApplicationContextUtil implements ApplicationContextAware
{
    private static ApplicationContext applicationContext = null;
    /** Creates a new instance of ApplicationContextUtil */
    public ApplicationContextUtil()
    {
    }
    public void setApplicationContext(ApplicationContext applicationContext)
                           throws BeansException
    {
        this.applicationContext = applicationContext;
    }
    public static ApplicationContext getApplicationContext()
    {
        return applicationContext;
    }
}
 


并做配置

<bean id="applicationContextUtil"
        class="ApplicationContextUtil"/>
 

我的项目中有些地方用到了工厂模式+策略模式,所以部分策略对象是由工厂动态提供,这种对象中如果要获得由spring管理的对象,就需要一个工具类,这个类通过上面第二种方式获得Spring应用上下文,然后拿到指定对象,代码如下:

public class SpringUtil implements ApplicationContextAware{
	private static ApplicationContext context;
	
	public SpringUtil(){
		
	}

	public static <T> T getObject(String id,Class<T> clazz) throws BeanNotOfRequiredTypeException,NoSuchBeanDefinitionException,BeansException{
		return context.getBean(id,clazz);
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		SpringUtil.context = applicationContext;
	}
}

你可能感兴趣的:(spring)