獲得spring裡註冊Bean的四種方法,特別是第三種方法,簡單:
一:方法一(多在struts架構中)繼承BaseDispatchAction
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中加上:
<bean id="serviceLocator" class="com.am.oa.commons.service.ServiceLocator" singleton="true" />
當對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);
}
}
action調用:
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;
}
}
三:方法三實現ApplicationContextAware
一定要在spring.xml中加上:
<bean id="SpringContextUtil " class="com.am.oa.commons.service.SpringContextUtil " singleton="true" />
當對SpringContextUtil 執行個體時就自動化佈建applicationContext,以便後來可直接用applicationContext
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);
}
}
action調用:
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;
}
}
四.通過servlet 或listener設定spring的ApplicationContext,以便後來引用.
注意分別extends ContextLoaderListener和ContextLoaderServlet .然後就可用SpringContext來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()));
}
}
例子:
第一步配置bean
<bean id="SpringContextUtil" class="com.hongdian.ibridge.util.SpringContextUtil" />
第二步建立bean
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
@SuppressWarnings("serial")
public class SpringContextUtil implements ApplicationContextAware {
public static ApplicationContext context; //Spring應用上下文環境
/**
* 實現ApplicationContextAware介面的回調方法,設定上下文環境
* @param applicationContext
* @throws BeansException
*/
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringContextUtil.context = context;
}
public static ApplicationContext getContext() {
return context;
}
/**
* @return ApplicationContext
*/
public static ApplicationContext getApplicationContext() {
return context;
}
/**
* 擷取對象
* @param name
* @return Object 一個以所給名字註冊的bean的執行個體
* @throws BeansException
*/
public static Object getBean(String name) throws BeansException {
return context.getBean(name);
}
}
得到bean
ApplicationContext context = SpringContextUtil.getContext();
IBaseService baseService = (IBaseService) context.getBean(BaseServiceImpl.class);
或者
IBaseService baseService = SpringContextUtil.context.getBean(BaseServiceImpl.class);