Filter 获取Context
在init()方法获取ServletContext,然后通过WebApplicationContextUtils.getWebApplicationContext(servletContext);
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
ServletContext servletContext = filterConfig.getServletContext();
WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext);
ssoClient = (SSOClient) ctx.getBean("ssoClient");
springRedisClient = (IRedisClient) ctx.getBean("springRedisClient");
}
Servlet 通过WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
public class ContextServlet extends HttpServlet {
public ApplicationContext getApplicationContext(){
return WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
}
}
其他Component组件获取ApplicationContext,一般来说可直接通过注解获取,但是,假如面试的话,也要知道
实现ApplicationContextAware接口即可