概述:最近作的兩個項目都用到了,因此想着把它整理起來方便之後用,很少說了,如今就將代碼附上java
個人活動平臺filter:web
public class SysFilter implements javax.servlet.Filter {spring
private IUserService userService;app
private IBasDao basDao;ide
@Override//在其初始化的時候獲取spa
public void init(FilterConfig filterConfig) throws ServletException {對象
//這裏面纔是關鍵所在get
ServletContext context = filterConfig.getServletContext();servlet
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);it
userService = (IUserService) ctx.getBean("userService");
basDao =(IBasDao)ctx.getBean("basDao");
//To change body of implemented methods use File | Settings | File Templates.
}
個人CRM項目Servlet:
public void init(ServletConfig servletConfig) throws ServletException { ServletContext servletContext = servletConfig.getServletContext(); WebApplicationContext webApplicationContext = WebApplicationContextUtils .getWebApplicationContext(servletContext); userService = (IUserService) ctx.getBean("userService"); 上面是我本身搞的,稍後我會將公司的也寫上去。 /** spring的conext對象 */ private static ApplicationContext applicationContext; public static ApplicationContext getApplicationContext() { return applicationContext; } public static void setApplicationContext(ApplicationContext applicationContext) { UtilSpring.applicationContext = applicationContext; }
public static <T> T getBeanByBeanId(String beanId) {
if (beanId==null)
return null;
if (beanId.equalsIgnoreCase(NULL_BEAN))
return null;
return (T)getBeanByBeanIdOrClass(beanId, null);
}
/**
* 根據beanId和bean類型從applicationContext中取得bean, 若applicationContext中存在beanId對應的bean則返回此bean
* 不然返回applicationContext中類型爲clazz的bean中的第一個
* @param beanId
* @param clazz
* @return
*/
public static Object getBeanByBeanIdOrClass(String beanId, Class clazz) {
if (applicationContext==null)
return null;
if (NULL_BEAN.equalsIgnoreCase(beanId))
return null;
if (beanId!=null)
if (applicationContext.containsBean(beanId))
return applicationContext.getBean(beanId);
List l=getBeansByClass(clazz);
if (l.size()>0)
return l.get(0);
return null;
}