filter里无法用Autowired获取bean
来源:互联网 发布:软件界面模糊 编辑:程序博客网 时间:2024/06/05 06:33
参考文章:https://www.zhihu.com/question/22977026/answer/23317656
获取Bean工具类:
https://www.cnblogs.com/duanxz/p/5463230.html
filter中获取bean的方法
web.xml中配置<filter> <filter-name>sessionFilter</filter-name> <filter-class>com.sung.risk.client.filter.SessionFilter</filter-class></filter><filter-mapping> <filter-name>sessionFilter</filter-name> <url-pattern>*.html</url-pattern></filter-mapping>private ProductService productService;@Overridepublic void init(FilterConfig filterConfig) throws ServletException { ServletContext servletContext = filterConfig.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(servletContext); productService = (ProductService)ctx.getBean("productService");}
众所周知,web应用启动的顺序是:listener->filter->servlet,而因为项目应用了spring mvc,所以我们会有两个配置文件(applixationContext.xml和springMVC-sevlet.xml),我们在配置spring时会用到spring的listener,它会读取application.xml里的配置对spring context进行初始化;而springMVC-servlet.xml则是在spring mvc的dispathServlet启动的时候读取进行配置。而如果项目里用到了注解,则需要在springMVC-servlet.xml中加上<context:component-scan>
。
ok,经过上面的铺垫后,进入重点。
问题就是项目启动时,先初始化listener,因此配置在applicationContext.xml里的bean会被初始化和注入;然后再来就filter的初始化,再接着才到我们的dispathServlet的初始化,因此,当我们需要在filter里注入一个注解的bean时,就会注入失败,因为filter初始化时,注解的bean还没初始化,没法注入。所以,如果想要在filter里注入注解bean的话,就要在applicationContext.xml里配置context,也就是上面说的那句配置。在这里配置时需要注意的是,需要把tx和aop的配置放在最下面,否则也会导致spring的context初始化失败。
把配置弄好之后,我们就在filter的init方法里,通过获取webApplicationContext的getBean方法对需要的bean进行注入。
- filter里无法用Autowired获取bean
- 在springMvc中的filter里用@Autowired注入bean
- Interceptor无法用Autowired自动注入Bean
- servlet中无法直接autowired bean from Spring
- filter获取 spring bean 或者service
- Filter中获取Spring的bean
- 怎样获取Spring工厂里的Bean
- Spring里遇到的一个问题,autowired时报找不到bean定义
- Spring用@Autowired注入Map类型Bean时报错解决
- new 出的对象,无法调用@Autowired进入的spring bean
- CXF中使用Autowired注解无法注入bean的有关问题
- new 出的对象,无法调用@Autowired进入的spring bean
- new出来的对象无法调用@Autowired注入的Spring Bean
- 页面无法获取list bean解决方法
- Filter或Servlet中获取Spring Bean的方法
- 在servlet、filter、Taglib中获取Spring Bean
- 在filter中获取spring容器中的bean对象
- spring @Autowired加载bean异常
- STM8 I/O口模拟I2C
- hdu 6161
- ViewPager实现源码分析
- Java写一个接口(包括token),第三方调用
- 类的组成:成员变量 成员方法 构造方法
- filter里无法用Autowired获取bean
- java并发的处理方式
- tomcat启动过程报the JDBC Driver has been forcibly unregistered问题的修复的一种方法
- java单例模式
- AngularJS orderBy 使用要点
- 广义相对论 狭义相对论 双生子
- 欢迎使用CSDN-markdown编辑器
- Android开发基本环境搭建
- Select 语句执行顺序以及如何提高Oracle 基本查询效率--原文链接http://www.cnblogs.com/likeju/p/5039128.html