Java_Web開発_SSHスプリングでBeanのインスタンスを取得する方法.
springにBeanを登録する4つの方法、特に3つ目の方法を取得します.簡単です.1つは、方法1(strutsフレームワークに多く含まれる)BaseDispatchActionを継承することです.
[java] view plaincopyprint?
二:方法二BeanFactoryAwareを実現するには必ずspring.xmlに追加:serviceLocatorインスタンスの場合、BeanFactoryが自動的に設定され、後でbeanFactoryを直接使用できるようになります
public class ServiceLocator implements BeanFactoryAware { private static BeanFactory beanFactory = null; private static ServiceLocator servlocator = null; public void setBeanFactory(BeanFactory factory) throws BeansException { this.beanFactory = factory; } public BeanFactory getBeanFactory() { return beanFactory; } public static ServiceLocator getInstance() { if (servlocator == null) servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator"); return servlocator; }/***提供されたbean名に基づいて対応するサービスクラス*@param servName bean名*/public static Object getService(String servName){return beanFactory.getBean(servName);}/***提供されたbean名に基づいて指定されたタイプのサービスクラス*@param servName bean名*@param clazzが返すbeanタイプが得られ、タイプが一致しないと例外*/public static Object getService(String servName,Class clazz){return beanFactory.getBean(servName,clazz); } }
アクションコール:
public class UserAction extends BaseAction implements Action,ModelDriven{ private Users user = new Users(); protected ServiceLocator service = ServiceLocator.getInstance(); UserService userService = (UserService)service.getService("userService"); public String execute() throws Exception { return SUCCESS; } public Object getModel() { return user; } public String getAllUser(){ HttpServletRequest request = ServletActionContext.getRequest(); List ls=userService.LoadAllObject( Users.class ); request.setAttribute("user",ls); this.setUrl("/yonghu.jsp"); return SUCCESS; } }
3.方法3.ApplicationContextAwareを実現するには必ずspring.xmlに:SpringContextUtilインスタンスの場合、アプリケーションContextを自動的に設定し、アプリケーションContextを直接使用できるようにします.
public class SpringContextUtil implements ApplicationContextAware{private static ApplicationContext applicationContext;//springアプリケーションコンテキスト環境/**ApplicationContextAwareインタフェースのコールバック方法を実装し、コンテキスト環境を設定する*@paramアプリケーションContext*@throws BeansException*/public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; }/***取得対象*@param name*@return Object名前で登録されたbeanのインスタンス*@throws BeansException*/public static Object getBean(String name)throws BeansException{returnアプリケーションContext.getBean(name);}/***取得タイプがrequiredTypeのオブジェクト*beanがタイプ変換できない場合、対応する例外が放出されます(BeanNotOfRequiredType Exception)*@param name bean登録名*@param requiredType戻りオブジェクトタイプ*@return Object戻りrequiredTypeオブジェクト*@throws BeansException*/public static Object getBean(String name,Class requiredType)throws BeansException{ return applicationContext.getBean(name, requiredType); }/***BeanFactoryに与えられた名前に一致するbean定義が含まれている場合は、true*@param name*@return boolean*/public static boolean containsBean(String name){returnアプリケーションContext.containsBean(name);}/***指定された名前で登録されたbean定義がsingletonかprototypeかを判断します.*指定された名前に対応するbean定義が見つからない場合、例外(NoSuchBeanDefinitionException)*@param name*@return boolean*@throws NoSuchBeanDefinitionException*/public static boolean isSingleton(String name)throws NoSuchBeanDefinitionException{return applicationContext.isSingleton(name);}/**@param name*@return Class登録オブジェクトのタイプ*@throws No SuchBeanDefinitionException*/public static Class getType(String name)throws No SuchBeanDefinitionException{return applicationContext.getType(name);}/***指定されたbean名がbean定義に別名がある場合、それらの別名*@param name*@return*@throws No SuchBeanDefinitionException*/public static String[]getAliases(String name)throws No SuchBeanDefinitionException{returnアプリケーションContext.getAliases(name); } }
アクションコール:
[java] view plaincopyprint?
package com.anymusic.oa.webwork; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.anymusic.oa.commons.service.ServiceLocator; import com.anymusic.oa.hibernate.pojo.Role; import com.anymusic.oa.hibernate.pojo.Users; import com.anymusic.oa.spring.IUserService; import com.opensymphony.webwork.ServletActionContext; import com.opensymphony.xwork.Action; import com.opensymphony.xwork.ActionContext; import com.opensymphony.xwork.ModelDriven; public class UserAction extends BaseAction implements Action,ModelDriven{private Users=new Users();//springContext.xmlファイルをロードする必要はありません.web.xmlで構成されているので、プログラムで起動すればあります.UserService=(UserService)SpringContextUtil.getBean("userService");public String execute()throws Exception{return SUCCESS; } public Object getModel() { return user; } public String getAllUser(){ HttpServletRequest request = ServletActionContext.getRequest(); List ls=userService.LoadAllObject( Users.class ); request.setAttribute("user",ls); this.setUrl("/yonghu.jsp"); return SUCCESS; } }
四.servletまたはlistenerでspringのApplicationContextを設定し、後で参照する.注意それぞれextends ContextLoaderListenerとContextLoaderServicelet.それからSpringContextでBeanをgetBeanすることができます.Web上で上書きxmlで構成されているlistenerまたはservlet.
public class SpringContext{private static ApplicationContext applicationContext;//springアプリケーションコンテキスト環境*/public void setApplicationContext(ApplicationContext applicationContext)throws BeansException{SpringContextUtil.applicationContext=applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } } public class SpringContextLoaderListener extends ContextLoaderListener{ //public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); SpringContext.setApplicationContext( WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()) ); } } public class SpringContextLoaderServlet extends ContextLoaderServlet { private ContextLoader contextLoader; public void init() throws ServletException { this.contextLoader = createContextLoader(); SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext())); } }
自分で使う:
1.アプリケーションContextファイルがsrcのルートディレクトリの下にある場合:
取得可能
2.ファイルがWebRoot/WEB-INFであれば使用可能
取得する
3.servletで利用可能な場合
songylwqのコラムを転載
[java] view plaincopyprint?
import com.mas.wawacommunity.wap.service.UserManager;
public class BaseDispatchAction extends DispatchAction {
/**
* web
*/
protected WebApplicationContext ctx;
protected UserManager userMgr;
/**
* Bean
* @param beanName String Bean
* @return
*/
protected final Object getBean(String beanName) {
return ctx.getBean(beanName);
}
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response) {
return mapping.findForward("index");
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
this.userMgr = (UserManager) getBean("userManager");
}
}
import com.mas.wawacommunity.wap.service.UserManager;
public class BaseDispatchAction extends DispatchAction {
/**
* web
*/
protected WebApplicationContext ctx;
protected UserManager userMgr;
/**
* Bean
* @param beanName String Bean
* @return
*/
protected final Object getBean(String beanName) {
return ctx.getBean(beanName);
}
protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
javax.servlet.http.HttpServletRequest request,
javax.servlet.http.HttpServletResponse response) {
return mapping.findForward("index");
}
public void setServlet(ActionServlet servlet) {
this.servlet = servlet;
this.ctx = WebApplicationContextUtils.getWebApplicationContext(servlet.getServletContext());
this.userMgr = (UserManager) getBean("userManager");
}
}
二:方法二BeanFactoryAwareを実現するには必ずspring.xmlに追加:
[java] view
plaincopyprint?
public class ServiceLocator implements BeanFactoryAware {
private static BeanFactory beanFactory = null;
private static ServiceLocator servlocator = null;
public void setBeanFactory(BeanFactory factory) throws BeansException {
this.beanFactory = factory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public static ServiceLocator getInstance() {
if (servlocator == null)
servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator");
return servlocator;
}
/**
* bean
* @param servName bean
*/
public static Object getService(String servName) {
return beanFactory.getBean(servName);
}
/**
* bean
* @param servName bean
* @param clazz bean , ,
*/
public static Object getService(String servName, Class clazz) {
return beanFactory.getBean(servName, clazz);
}
}
public class ServiceLocator implements BeanFactoryAware { private static BeanFactory beanFactory = null; private static ServiceLocator servlocator = null; public void setBeanFactory(BeanFactory factory) throws BeansException { this.beanFactory = factory; } public BeanFactory getBeanFactory() { return beanFactory; } public static ServiceLocator getInstance() { if (servlocator == null) servlocator = (ServiceLocator) beanFactory.getBean("serviceLocator"); return servlocator; }/***提供されたbean名に基づいて対応するサービスクラス*@param servName bean名*/public static Object getService(String servName){return beanFactory.getBean(servName);}/***提供されたbean名に基づいて指定されたタイプのサービスクラス*@param servName bean名*@param clazzが返すbeanタイプが得られ、タイプが一致しないと例外*/public static Object getService(String servName,Class clazz){return beanFactory.getBean(servName,clazz); } }
アクションコール:
[java] view
plaincopyprint?
public class UserAction extends BaseAction implements Action,ModelDriven{
private Users user = new Users();
protected ServiceLocator service = ServiceLocator.getInstance();
UserService userService = (UserService)service.getService("userService");
public String execute() throws Exception {
return SUCCESS;
}
public Object getModel() {
return user;
}
public String getAllUser(){
HttpServletRequest request = ServletActionContext.getRequest();
List ls=userService.LoadAllObject( Users.class );
request.setAttribute("user",ls);
this.setUrl("/yonghu.jsp");
return SUCCESS;
}
}
public class UserAction extends BaseAction implements Action,ModelDriven{ private Users user = new Users(); protected ServiceLocator service = ServiceLocator.getInstance(); UserService userService = (UserService)service.getService("userService"); public String execute() throws Exception { return SUCCESS; } public Object getModel() { return user; } public String getAllUser(){ HttpServletRequest request = ServletActionContext.getRequest(); List ls=userService.LoadAllObject( Users.class ); request.setAttribute("user",ls); this.setUrl("/yonghu.jsp"); return SUCCESS; } }
3.方法3.ApplicationContextAwareを実現するには必ずspring.xmlに:
[java] view
plaincopyprint?
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext; //Spring
/**
* ApplicationContextAware ,
* @param applicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
*
* @param name
* @return Object bean
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
/**
* requiredType
* bean , (BeanNotOfRequiredTypeException)
* @param name bean
* @param requiredType
* @return Object requiredType
* @throws BeansException
*/
public static Object getBean(String name, Class requiredType) throws BeansException {
return applicationContext.getBean(name, requiredType);
}
/**
* BeanFactory bean , true
* @param name
* @return boolean
*/
public static boolean containsBean(String name) {
return applicationContext.containsBean(name);
}
/**
* bean singleton prototype。
* bean , (NoSuchBeanDefinitionException)
* @param name
* @return boolean
* @throws NoSuchBeanDefinitionException
*/
public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
return applicationContext.isSingleton(name);
}
/**
* @param name
* @return Class
* @throws NoSuchBeanDefinitionException
*/
public static Class getType(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getType(name);
}
/**
* bean bean ,
* @param name
* @return
* @throws NoSuchBeanDefinitionException
*/
public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
return applicationContext.getAliases(name);
}
}
public class SpringContextUtil implements ApplicationContextAware{private static ApplicationContext applicationContext;//springアプリケーションコンテキスト環境/**ApplicationContextAwareインタフェースのコールバック方法を実装し、コンテキスト環境を設定する*@paramアプリケーションContext*@throws BeansException*/public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringContextUtil.applicationContext = applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; }/***取得対象*@param name*@return Object名前で登録されたbeanのインスタンス*@throws BeansException*/public static Object getBean(String name)throws BeansException{returnアプリケーションContext.getBean(name);}/***取得タイプがrequiredTypeのオブジェクト*beanがタイプ変換できない場合、対応する例外が放出されます(BeanNotOfRequiredType Exception)*@param name bean登録名*@param requiredType戻りオブジェクトタイプ*@return Object戻りrequiredTypeオブジェクト*@throws BeansException*/public static Object getBean(String name,Class requiredType)throws BeansException{ return applicationContext.getBean(name, requiredType); }/***BeanFactoryに与えられた名前に一致するbean定義が含まれている場合は、true*@param name*@return boolean*/public static boolean containsBean(String name){returnアプリケーションContext.containsBean(name);}/***指定された名前で登録されたbean定義がsingletonかprototypeかを判断します.*指定された名前に対応するbean定義が見つからない場合、例外(NoSuchBeanDefinitionException)*@param name*@return boolean*@throws NoSuchBeanDefinitionException*/public static boolean isSingleton(String name)throws NoSuchBeanDefinitionException{return applicationContext.isSingleton(name);}/**@param name*@return Class登録オブジェクトのタイプ*@throws No SuchBeanDefinitionException*/public static Class getType(String name)throws No SuchBeanDefinitionException{return applicationContext.getType(name);}/***指定されたbean名がbean定義に別名がある場合、それらの別名*@param name*@return*@throws No SuchBeanDefinitionException*/public static String[]getAliases(String name)throws No SuchBeanDefinitionException{returnアプリケーションContext.getAliases(name); } }
アクションコール:
[java] view plaincopyprint?
package com.anymusic.oa.webwork;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import com.anymusic.oa.commons.service.ServiceLocator;
import com.anymusic.oa.hibernate.pojo.Role;
import com.anymusic.oa.hibernate.pojo.Users;
import com.anymusic.oa.spring.IUserService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.Action;
import com.opensymphony.xwork.ActionContext;
import com.opensymphony.xwork.ModelDriven;
public class UserAction extends BaseAction implements Action,ModelDriven{
private Users user = new Users();
// springContext.xml , web.xml , .
UserService userService = (UserService) SpringContextUtil.getBean("userService");
public String execute() throws Exception {
return SUCCESS;
}
public Object getModel() {
return user;
}
public String getAllUser(){
HttpServletRequest request = ServletActionContext.getRequest();
List ls=userService.LoadAllObject( Users.class );
request.setAttribute("user",ls);
this.setUrl("/yonghu.jsp");
return SUCCESS;
}
}
package com.anymusic.oa.webwork; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import com.anymusic.oa.commons.service.ServiceLocator; import com.anymusic.oa.hibernate.pojo.Role; import com.anymusic.oa.hibernate.pojo.Users; import com.anymusic.oa.spring.IUserService; import com.opensymphony.webwork.ServletActionContext; import com.opensymphony.xwork.Action; import com.opensymphony.xwork.ActionContext; import com.opensymphony.xwork.ModelDriven; public class UserAction extends BaseAction implements Action,ModelDriven{private Users=new Users();//springContext.xmlファイルをロードする必要はありません.web.xmlで構成されているので、プログラムで起動すればあります.UserService=(UserService)SpringContextUtil.getBean("userService");public String execute()throws Exception{return SUCCESS; } public Object getModel() { return user; } public String getAllUser(){ HttpServletRequest request = ServletActionContext.getRequest(); List ls=userService.LoadAllObject( Users.class ); request.setAttribute("user",ls); this.setUrl("/yonghu.jsp"); return SUCCESS; } }
四.servletまたはlistenerでspringのApplicationContextを設定し、後で参照する.注意それぞれextends ContextLoaderListenerとContextLoaderServicelet.それからSpringContextでBeanをgetBeanすることができます.Web上で上書きxmlで構成されているlistenerまたはservlet.
[java] view
plaincopyprint?
public class SpringContext {
private static ApplicationContext applicationContext; //Spring
*/
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextUtil.applicationContext = applicationContext;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
*/
public static Object getBean(String name) throws BeansException {
return applicationContext.getBean(name);
}
}
public class SpringContextLoaderListener extends ContextLoaderListener{ //
public void contextInitialized(ServletContextEvent event) {
super.contextInitialized(event);
SpringContext.setApplicationContext(
WebApplicationContextUtils.getWebApplicationContext(event.getServletContext())
);
}
}
public class SpringContextLoaderServlet extends ContextLoaderServlet {
private ContextLoader contextLoader;
public void init() throws ServletException {
this.contextLoader = createContextLoader();
SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext()));
}
}
public class SpringContext{private static ApplicationContext applicationContext;//springアプリケーションコンテキスト環境*/public void setApplicationContext(ApplicationContext applicationContext)throws BeansException{SpringContextUtil.applicationContext=applicationContext; } /** * @return ApplicationContext */ public static ApplicationContext getApplicationContext() { return applicationContext; } */ public static Object getBean(String name) throws BeansException { return applicationContext.getBean(name); } } public class SpringContextLoaderListener extends ContextLoaderListener{ //public void contextInitialized(ServletContextEvent event) { super.contextInitialized(event); SpringContext.setApplicationContext( WebApplicationContextUtils.getWebApplicationContext(event.getServletContext()) ); } } public class SpringContextLoaderServlet extends ContextLoaderServlet { private ContextLoader contextLoader; public void init() throws ServletException { this.contextLoader = createContextLoader(); SpringContext.setApplicationContext(this.contextLoader.initWebApplicationContext(getServletContext())); } }
自分で使う:
1.アプリケーションContextファイルがsrcのルートディレクトリの下にある場合:
ApplicationContext apt= new
FileSystemXmlApplicationContext("src/applicationContext.xml");
apt.getBean("ID");
取得可能
2.ファイルがWebRoot/WEB-INFであれば使用可能
ApplicationContext applicationContext= new
FileSystemXmlApplicationContext("../applicationContext.xml");
取得する
3.servletで利用可能な場合
ServletContext application =
this.getServletContext();
// spring
servlet
WebApplicationContext wac =
WebApplicationContextUtils.getWebApplicationContext(application);
IDicService
dicService = (IDicService)wac.getBean("dicService");
songylwqのコラムを転載