ssh 架构上 怎么获得 applicationcontext 和spring 管理的 bean 和
ssh 架构下 如何获得 applicationcontext 和spring 管理的 bean 和
如果 是在自己定义的bean中 获得 applicationcontext 可以让该bean 实现applicationcontextaware接口 ,记得把这个bean 配置在 spring的配置文件里 ,
源码如下bean 的java文件定义如下
package com.my.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MyApplicationContext implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
// TODO Auto-generated method stub
this.applicationContext=ac;
}
public ApplicationContext getApplicationContext(){
return applicationContext;
//String[] str=new String[4];
}
}
spring 的配置如下
<bean id="myapplicationcontext" class="com.my.utils.MyApplicationContext" >
</bean>
当你需要 在action中使用时 ,只需要 将该bean 注入 到action 中 通过该bean 即可获得 applicationcontext,从而通过 applicationcontext.getbean(“bean的id")获得 需要的bean;
如果 在 非spring管理的类中要获得applicationcontext 可以使用如下方式
HttpServletRequest httprequest=(HttpServletRequest)ServletActionContext.getRequest();
ServletContext sc=httprequest.getSession().getServletContext();
ApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(sc);
然后 通过wac的getbean方法 获取你想要的bean
如果 是在自己定义的bean中 获得 applicationcontext 可以让该bean 实现applicationcontextaware接口 ,记得把这个bean 配置在 spring的配置文件里 ,
源码如下bean 的java文件定义如下
package com.my.utils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class MyApplicationContext implements ApplicationContextAware {
private ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
// TODO Auto-generated method stub
this.applicationContext=ac;
}
public ApplicationContext getApplicationContext(){
return applicationContext;
//String[] str=new String[4];
}
}
spring 的配置如下
<bean id="myapplicationcontext" class="com.my.utils.MyApplicationContext" >
</bean>
当你需要 在action中使用时 ,只需要 将该bean 注入 到action 中 通过该bean 即可获得 applicationcontext,从而通过 applicationcontext.getbean(“bean的id")获得 需要的bean;
如果 在 非spring管理的类中要获得applicationcontext 可以使用如下方式
HttpServletRequest httprequest=(HttpServletRequest)ServletActionContext.getRequest();
ServletContext sc=httprequest.getSession().getServletContext();
ApplicationContext wac=WebApplicationContextUtils.getWebApplicationContext(sc);
然后 通过wac的getbean方法 获取你想要的bean