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.
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.
本文介绍了一种无需将整个应用整合到Spring框架中即可使用Spring Bean的方法。通过创建一个实现了ApplicationContextAware接口的静态类SpringContext,并将其配置在application-context.xml文件中,可以在任何需要的地方轻松获取Spring Bean实例。
1万+

被折叠的 条评论
为什么被折叠?



