概述:最近做的两个项目都用到了,所以想着把它整理起来方便以后用,不多说了,现在就将代码附上

我的活动平台filter:

public class SysFilter implements javax.servlet.Filter {

    private IUserService userService;

    private IBasDao basDao;


    @Override//在其初始化的时候获取

    public void init(FilterConfig filterConfig) throws ServletException {

        //这里面才是关键所在

        ServletContext context = filterConfig.getServletContext();

        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);

        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;

}