filter、servlet引用springmvc註解

概述:最近做的兩個項目都用到了,所以想着把它整理起來方便以後用,不多說了,現在就將代碼附上

我的活動平臺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;

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章