web中spring获取bean
最近在用mybatis+spring,但是因为数据库是集群,所以要对sqlsession或者sessionFactoryBean分开管理,就要通过bean分别获取session,并且为了serviceAction和model的解耦,所以就想在model层引入session,平时session和事务之所以放在control层管理,就是因为一般这一层是直接访问bean,所以里面在这里注入session和事务可以直接获得springapplicationContext中的bean,要我现在为了解耦(实际上在这里通过@Autowried(request=true/false)只是编译解耦运行实际是不解偶的,因为不申明Autowried下的bean编译可以通过但是运行会报错,beanCreateException)就想在model层来获取bean,下面的文章写的不错
http://dearseven.blog.163.com/blog/static/10053792220122410381684/
获得spring里注册Bean的四种方法,特别是第三种方法,简单:
一:方法一(多在struts框架中)继承BaseDispatchAction
importcom.mas.wawacommunity.wap.service.UserManager;
publicclassBaseDispatchActionextendsDispatchAction{
/**
*web应用上下文环境变量
*/
protectedWebApplicationContextctx;
protectedUserManageruserMgr;
/**
*获得注册Bean
*@parambeanNameString注册Bean的名称
*@return
*/
protectedfinalObjectgetBean(StringbeanName){
returnctx.getBean(beanName);
}
protectedActionForwardunspecified(ActionMappingmapping,ActionFormform,
javax.servlet.http.HttpServletRequestrequest,
javax.servlet.http.HttpServletResponseresponse){
returnmapping.findForward("index");
}
publicvoidsetServlet(ActionServletservlet){
this.servlet=servlet;
this.ctx=WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
this.userMgr=(UserManager)getBean("userManager");
}
}
二:方法二实现BeanFactoryAware
一定要在spring.xml中加上:
<beanid="serviceLocator"class="com.am.oa.commons.service.ServiceLocator"singleton="true"/>
当对serviceLocator实例时就自动设置BeanFactory,以便后来可直接用beanFactory
publicclassServiceLocatorimplementsBeanFactoryAware{
privatestaticBeanFactorybeanFactory=null;
privatestaticServiceLocatorservlocator=null;
publicvoidsetBeanFactory(BeanFactoryfactory)throwsBeansException{
this.beanFactory=factory;
}
publicBeanFactorygetBeanFactory(){
returnbeanFactory;
}
publicstaticServiceLocatorgetInstance(){
if(servlocator==null)
servlocator=(ServiceLocator)beanFactory.getBean("serviceLocator");
returnservlocator;
}
/**
*根据提供的bean名称得到相应的服务类
*@paramservNamebean名称
*/
publicstaticObjectgetService(StringservName){
returnbeanFactory.getBean(servName);
}
/**
*根据提供的bean名称得到对应于指定类型的服务类
*@paramservNamebean名称
*@paramclazz返回的bean类型,若类型不匹配,将抛出异常
*/
publicstaticObjectgetService(StringservName,Classclazz){
returnbeanFactory.getBean(servName,clazz);
}
}
action调用:
publicclassUserActionextendsBaseActionimplementsAction,ModelDriven{
privateUsersuser=newUsers();
protectedServiceLocatorservice=ServiceLocator.getInstance();
UserServiceuserService=(UserService)service.getService("userService");
publicStringexecute()throwsException{
returnSUCCESS;
}
publicObjectgetModel(){
returnuser;
}
publicStringgetAllUser(){
HttpServletRequestrequest=ServletActionContext.getRequest();
Listls=userService.LoadAllObject(Users.class);
request.setAttribute("user",ls);
this.setUrl("/yonghu.jsp");
returnSUCCESS;
}
}
三:方法三实现ApplicationContextAware
一定要在spring.xml中加上:
<beanid="SpringContextUtil"class="com.am.oa.commons.service.SpringContextUtil"singleton="true"/>
当对SpringContextUtil实例时就自动设置applicationContext,以便后来可直接用applicationContext
publicclassSpringContextUtilimplementsApplicationContextAware{
privatestaticApplicationContextapplicationContext;//Spring应用上下文环境
/**
*实现ApplicationContextAware接口的回调方法,设置上下文环境
*@paramapplicationContext
*@throwsBeansException
*/
publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{
SpringContextUtil.applicationContext=applicationContext;
}
/**
*@returnApplicationContext
*/
publicstaticApplicationContextgetApplicationContext(){
returnapplicationContext;
}
/**
*获取对象
*@paramname
*@returnObject一个以所给名字注册的bean的实例
*@throwsBeansException
*/
publicstaticObjectgetBean(Stringname)throwsBeansException{
returnapplicationContext.getBean(name);
}
/**
*获取类型为requiredType的对象
*如果bean不能被类型转换,相应的异常将会被抛出(BeanNotOfRequiredTypeException)
*@paramnamebean注册名
*@paramrequiredType返回对象类型
*@returnObject返回requiredType类型对象
*@throwsBeansException
*/
publicstaticObjectgetBean(Stringname,ClassrequiredType)throwsBeansException{
returnapplicationContext.getBean(name,requiredType);
}
/**
*如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
*@paramname
*@returnboolean
*/
publicstaticbooleancontainsBean(Stringname){
returnapplicationContext.containsBean(name);
}
/**
*判断以给定名字注册的bean定义是一个singleton还是一个prototype。
*如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
*@paramname
*@returnboolean
*@throwsNoSuchBeanDefinitionException
*/
publicstaticbooleanisSingleton(Stringname)throwsNoSuchBeanDefinitionException{
returnapplicationContext.isSingleton(name);
}
/**
*@paramname
*@returnClass注册对象的类型
*@throwsNoSuchBeanDefinitionException
*/
publicstaticClassgetType(Stringname)throwsNoSuchBeanDefinitionException{
returnapplicationContext.getType(name);
}
/**
*如果给定的bean名字在bean定义中有别名,则返回这些别名
*@paramname
*@return
*@throwsNoSuchBeanDefinitionException
*/
publicstaticString[]getAliases(Stringname)throwsNoSuchBeanDefinitionException{
returnapplicationContext.getAliases(name);
}
}
action调用:
packagecom.anymusic.oa.webwork;
importjava.util.List;
importjava.util.Map;
importjavax.servlet.http.HttpServletRequest;
importcom.anymusic.oa.commons.service.ServiceLocator;
importcom.anymusic.oa.hibernate.pojo.Role;
importcom.anymusic.oa.hibernate.pojo.Users;
importcom.anymusic.oa.spring.IUserService;
importcom.opensymphony.webwork.ServletActionContext;
importcom.opensymphony.xwork.Action;
importcom.opensymphony.xwork.ActionContext;
importcom.opensymphony.xwork.ModelDriven;
publicclassUserActionextendsBaseActionimplementsAction,ModelDriven{
privateUsersuser=newUsers();
//不用再加载springContext.xml文件,因为在web.xml中配置了,在程序中启动是就有了.
UserServiceuserService=(UserService)SpringContextUtil.getBean("userService");
publicStringexecute()throwsException{
returnSUCCESS;
}
publicObjectgetModel(){
returnuser;
}
publicStringgetAllUser(){
HttpServletRequestrequest=ServletActionContext.getRequest();
Listls=userService.LoadAllObject(Users.class);
request.setAttribute("user",ls);
this.setUrl("/yonghu.jsp");
returnSUCCESS;
}
}
四.通过servlet或listener设置spring的ApplicationContext,以便后来引用.
注意分别extendsContextLoaderListener和ContextLoaderServlet.然后就可用SpringContext来getBean.
覆盖原来在web.xml中配置的listener或servlet.
publicclassSpringContext{
privatestaticApplicationContextapplicationContext;//Spring应用上下文环境
*/
publicvoidsetApplicationContext(ApplicationContextapplicationContext)throwsBeansException{
SpringContextUtil.applicationContext=applicationContext;
}
/**
*@returnApplicationContext
*/
publicstaticApplicationContextgetApplicationContext(){
returnapplicationContext;
}
*/
publicstaticObjectgetBean(Stringname)throwsBeansException{
returnapplicationContext.getBean(name);
}
}
publicclassSpringContextLoaderListenerextendsContextLoaderListener{//
publicvoidcontextInitialized(ServletContextEventevent){
super.contextInitialized(event);
SpringContext.setApplicationContext(
WebApplicationContextUtils.getWebApplicationContext(event.getServletContext())
);
}
}
publicclassSpringContextLoaderServletextendsContextLoaderServlet{
privateContextLoadercontextLoader;
publicvoidinit()throwsServletException{
this.contextLoader=createContextLoader();
SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext()));
}
}