Gaining Access to the Spring Context in Non Spring Managed Classes
2016-04-15 15:31
676 查看
There are times where it’s not practical (or possible) to wire up your entire application into the Spring framework, but you still need a Spring loaded bean in order to perform a task. JSP tags and legacy code are two such examples. Here is a quick and easy
way to get access to the application context.
First we create a class that has a dependency on the spring context. The magic here is a combination of implementing ApplicationContextAware and defining the ApplicatonContext object as static.
Next, we wire SpringContext into our spring container by defining it in our application-context.xml:
Now, anywhere we need access to the spring context we can import SpringContext and call the getApplicationContext method like so:
Keep in mind that if there are multiple spring containers running on the JVM the static ApplicationContext object will be overwritten by the last container loaded so this approach may not work for you.
way to get access to the application context.
First we create a class that has a dependency on the spring context. The magic here is a combination of implementing ApplicationContextAware and defining the ApplicatonContext object as static.
package com.objectpartners.util; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; public class SpringContext implements ApplicationContextAware { private static ApplicationContext context; public void setApplicationContext(ApplicationContext context) throws BeansException { this.context = context; } public static ApplicationContext getApplicationContext() { return context;
} }
Next, we wire SpringContext into our spring container by defining it in our application-context.xml:
<bean id="springContext" class="com.objectpartners.util.SpringContext />
Now, anywhere we need access to the spring context we can import SpringContext and call the getApplicationContext method like so:
import com.objectpartners.util.SpringContext; class LegacyCode { . . SpringBean bean = (SpringBean)SpringContext.getApplicationContext.getBean("springBean"); . . }
Keep in mind that if there are multiple spring containers running on the JVM the static ApplicationContext object will be overwritten by the last container loaded so this approach may not work for you.
相关文章推荐
- java poi下载地址
- Windows7部署Android开发环境傻瓜式教程(Eclipse+ADT) (转)
- Java 数据存储
- Java中接口和抽象类的区别及使用的场合
- java thrift返回List<String>异常
- 安装JDK
- 共同学习Java源码--常用数据类型--String(十五)
- Struts2图片的上传下载
- Spring Boot使用自定义的properties
- java list排序
- Spring @PropertySource example
- 浅谈Java回调机制的简单理解
- Java基础之理解Annotation(自定义注解)
- JavaCard free memory detect (how much memory left)
- spring-工具类
- spring+jpa 两个数据源配置
- Eclipse插件Fat Jar的安装及使用
- java--集合的迭代器
- Java图形界面实战如何用键盘控制小球的移动以及接口的讲解
- Java异常捕获之try-catch-finally-return的执行顺序-转载