项目中调用service层方法
-
King
使用的工具类
package com.fltd.tourism.util;
import java.util.Locale;
import java.util.Map;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
/**
* 获取applicationContext对象
*
* @return
*/
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
return (T) applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> clazz) {
System.out.println(applicationContext);
return applicationContext.getBean(clazz);
}
/**
* 根据bean的id来查找对�?
*
* @param id
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getBeanById(String id) {
return (T) applicationContext.getBean(id);
}
/**
* 根据bean的class来查找对�?
*
* @param c
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> T getBeanByClass(Class c) {
return (T) applicationContext.getBean(c);
}
/**
* 根据bean的class来查找所有的对象(包括子类)
*
* @param c
* @return
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map getBeansByClass(Class c) {
return applicationContext.getBeansOfType(c);
}
public static String getMessage(String key) {
return applicationContext.getMessage(key, null, Locale.getDefault());
}
}
知识兔使用方法:
SpringContextUtil.getBean(xxxService.class).xxxmethod();
知识兔或者使用
在项目中遇到一个问题,在 Filter中注入 Serivce失败,注入的service始终为null。如下所示:
1 public class WeiXinFilter implements Filter{
2
3 @Autowired
4 private UsersService usersService;
5
6 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
7 HttpServletRequest req = (HttpServletRequest)request;
8 HttpServletResponse resp = (HttpServletResponse)response;
9 Users users = this.usersService.queryByOpenid(openid);
10 }
知识兔 上面的 usersService 会报空指针异常。
解决方法一:
1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
2 HttpServletRequest req = (HttpServletRequest)request;
3 HttpServletResponse resp = (HttpServletResponse)response;
4 ServletContext sc = req.getSession().getServletContext();
5 XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
6
7 if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
8 usersService = (UsersService) cxt.getBean("usersService");
9
10 Users users = this.usersService.queryByOpenid(openid);
知识兔 解决方法二:
public class WeiXinFilter implements Filter{
private UsersService usersService;
public void init(FilterConfig fConfig) throws ServletException {
ServletContext sc = fConfig.getServletContext();
XmlWebApplicationContext cxt = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(sc);
if(cxt != null && cxt.getBean("usersService") != null && usersService == null)
usersService = (UsersService) cxt.getBean("usersService");
}
知识兔 相关原理:
1. 如何获取 ServletContext:
1)在javax.servlet.Filter中直接获取
ServletContext context = config.getServletContext();
2)在HttpServlet中直接获取
this.getServletContext()
3)在其他方法中,通过HttpServletRequest获得
request.getSession().getServletContext();
2. WebApplicationContext 与 ServletContext (转自:http://blessht.iteye.com/blog/2121845):
Spring的 ContextLoaderListener是一个实现了ServletContextListener接口的监听器,在启动项目时会触发contextInitialized方法(该方法主要完成ApplicationContext对象的创建),在关闭项目时会触发contextDestroyed方法(该方法会执行ApplicationContext清理操作)。
ConextLoaderListener加载Spring上下文的过程
①启动项目时触发contextInitialized方法,该方法就做一件事:通过父类contextLoader的initWebApplicationContext方法创建Spring上下文对象。
②initWebApplicationContext方法做了三件事:创建 WebApplicationContext;加载对应的Spring文件创建里面的Bean实例;将WebApplicationContext放入 ServletContext(就是Java Web的全局变量)中。
③createWebApplicationContext创建上下文对象,支持用户自定义的上下文对象,但必须继承自ConfigurableWebApplicationContext,而Spring MVC默认使用ConfigurableWebApplicationContext作为ApplicationContext(它仅仅是一个接口)的实 现。
④configureAndRefreshWebApplicationContext方法用 于封装ApplicationContext数据并且初始化所有相关Bean对象。它会从web.xml中读取名为 contextConfigLocation的配置,这就是spring xml数据源设置,然后放到ApplicationContext中,最后调用传说中的refresh方法执行所有Java对象的创建。
⑤完成ApplicationContext创建之后就是将其放入ServletContext中,注意它存储的key值常量。
解决方法三:
直接使用spring mvc中的HandlerInterceptor或者HandlerInterceptorAdapter 来替换Filter:
public class WeiXinInterceptor implements HandlerInterceptor {
@Autowired
private UsersService usersService;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// TODO Auto-generated method stub
return false;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
// TODO Auto-generated method stub
}
}
知识兔 配置拦截路径:
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="net.xxxx.interceptor.WeiXinInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
知识兔