I have read related anwsers of how to inject beans into Custom servlets and i achieved to inject beans without scope, but when i try to inject a session bean it is not being injected and breaks with a NullPointer, below my code:
My Custom filter:
@Component
public class MyCustomFilter implements Filter{
@Inject
private MyService myService;
@Inject
private MyServiceWithSessionScope mySessionService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
//Works perfect!
myService.someMethod
//Is NULL
mySessionService
}
My Bean definition:
@Service("MyService")
public class MyService {
My Bean with scope definition:
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class MyServiceWithSessionScope {
The error i got is not helping me..
java.lang.NullPointerException
at org.springframework.web.context.request.SessionScope.get(SessionScope.java:92)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:337)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.aop.target.SimpleBeanTargetSource.getTarget(SimpleBeanTargetSource.java:35)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.getTarget(CglibAopProxy.java:685)
Why this is happening? Is there some way i should "initialize" the session?, sorry i am pretty lost in here, Thanks in advance!
EDIT :
So i register the filter using DelegatingFilterProxy but still is get Null :
public class MyWebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
DelegatingFilterProxy delegatingFilterProxy = new DelegatingFilterProxy();
delegatingFilterProxy.setBeanName("MyCustomFilter");
delegatingFilterProxy.setTargetBeanName("MyCustomFilter");
FilterRegistration.Dynamic myFiler = servletContext.addFilter("MyCustomFilter", delegatingFilterProxy);
myFiler.addMappingForUrlPatterns(null, false, "/somePath/*");