您的位置:首页 > 编程语言 > Java开发

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.
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: