Reputation: 423
For the project that we create during my formation we use spring to make dependency injection.
we have a servlet-context.xml file with the following configuration:
<context:component-scan base-package="fr.autoquiz3000" />
I created several controllers and I have no problem injecting the dao for example:
package fr.autoquiz3000;
@Controller
@RequestMapping("/public")
public class PublicController {
@Autowired
private UserDao uDao;
@GetMapping("/connection")
public ModelAndView getConnection() {
return new ModelAndView("public/viewConnexion");
}
but I try to create a filter with a dao like this:
package fr.autoquiz3000;
@Component
public class CountQuizStudent implements Filter {
@Autowired
private QuizToDoDao qtdDao;
and I have this error:
qtdDao= null
java.lang.NullPointerException
at fr.autoquiz3000.CountQuizStudent.doFilter(CountQuizStudent.java:41)
Someone could explain to me what I'm doing wrong!
thank you!
Upvotes: 0
Views: 33
Reputation: 429
For filters override init method and set Spring beans there:
@Override
public void init(FilterConfig filterConfig) throws ServletException {
WebApplicationContext springContext =
WebApplicationContextUtils.getWebApplicationContext(filterConfig.getServletContext());
userDao = springContext.getBean(UserDao.class);
}
or use DelegatingFilterProxy:
<filter>
<filter-name>yourFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>yourFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
@Component("yourFilter")
public class YourFilter implements Filter {
// auto wiring available as it's just Spring Bean
}
Upvotes: 1