普通Java类获取Spring的ApplicationContext
在SSH集成的前提下。某些情况我们需要在Action以外的类中来获得SPRing所管理的Service对象。
之前我在网上找了好几好久都没有找到合适的方法。例如:
ApplicationContext context = new ClassPathXmlApplicationContext();
当时我觉得没有这个必要,浪费内存。后来我终于想出了一个解决方法。在此拿来给大家参考下,希望对大家有帮助。
1.创建一个类并让其实现org.springframework.context.ApplicationContextAware接口来让Spring在启动的时候为我们注入ApplicationContext对象.
示例代码:
view plaincopy to clipboardprint?
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
ublic class MyApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;//声明一个静态变量保存
@Override
public void setApplicationContext(ApplicationContext contex)
throws BeansException {
this.context=contex;
}
public static ApplicationContext getContext(){
return context;
}
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MyApplicationContextUtil implements ApplicationContextAware {
private static ApplicationContext context;//声明一个静态变量保存
@Override
public void setApplicationContext(ApplicationContext contex)
throws BeansException {
this.context=contex;
}
public static ApplicationContext getContext(){
return context;
}
}
2.在applicationContext.xml文件中配置此bean,以便让Spring启动时自动为我们注入ApplicationContext对象.
例:
<!-- 这个bean主要是为了得到ApplicationContext 所以它不需要其它属性-->
<bean class="org.ing.springutil.MyApplicationContextUtil"></bean>
3.有了这个ApplicationContext之后我们就可以调用其getBean("beanName")方法来得到由Spring 管理所有对象.
----------------结束------------
分享到:
相关推荐
主要介绍了 Spring获取ApplicationContext对象工具类的实现方法的相关资料,希望通过本文能帮助到大家,让大家实现这样的功能,需要的朋友可以参考下
Spring中ApplicationContext加载机制
Spring中ApplicationContext和beanfactory区别.rar
Spring中ApplicationContext对事件传递
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean" p:dataSource-ref="dataSourceProxy"> <value>classpath:SqlMapConfig.xml</value> </property> ...
《Spring的数据源配置文件模板》applicationContext.zip
spring 获得applicationcontext公用方法
Spring ApplicationContext.xml配置的12个技巧演示教学.pdf
applicationContext applicationContext
Spring获取webapplicationcontext,applicationcontext几种方法详解
本篇文章主要介绍了详解spring applicationContext.xml 配置文件 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
spring的Applicationcontext对事件的监听,在一个applicationContext范围内,实现类似MQ的效果
applicationContext.xml+hiberniate属性+Session属性+自动代理+拦截器!!!! 上传的限制去除了jar包!
Spring配置文件ApplicationContext,内容齐全,有需要的可以下载。
Spring applicationContext.xml常见部分属性的使用备注
今天小编就为大家分享一篇关于spring中通过ApplicationContext getBean获取注入对象的方法实例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
Spring Web MVC开发 xml配置文件格式,无bean之类 Spring Web MVC开发配置文件 applicationContext
4.测试:启动Spring,获取Hello示例。 二、Spring基于XML装配实验 说明:使用Spring IOC模拟实现账户添加功能程序 1.创建JavaBean类:Account.java 2.创建DAO类: AccountDao.java,模拟账户添加操作 3.创建Service...
java ApplicationContext类继承体系.jpg
SpringUtil工具类(获取applicationContext,通过name获取 Bean,通过class获取Bean,通过name,以及Clazz返回)