我已经阅读了有关如何将bean注入到自定义servlet中的相关问题,并且我实现了注入没有范围的bean,但是当我尝试注入会话bean时,它没有被注入并且在我的代码下面用NullPointer打破: / p>
我的自定义过滤器:
@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定义:
@Service("MyService")
public class MyService {
我的Bean有范围定义:
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class MyServiceWithSessionScope {
我得到的错误并没有帮助我..
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)
为什么会这样?有什么方法可以“初始化”会话吗?对不起,我在这里很丢失, 提前谢谢!
编辑:
所以我使用DelegatingFilterProxy注册过滤器,但仍然是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/*");