I'm developing a web app with Spring 4.1.7 and Hibernate 4.3.10. I needed to create an Interceptor for manage transactions like this:
public class ControllerInterceptor extends HandlerInterceptorAdapter
{
@Autowired
private SessionFactory sessionFactory;
private Session session;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception
{
super.preHandle(request, response, handler);
ControllerInterceptor ci = this;
session = sessionFactory.getCurrentSession();
//Transaction management....
return true;
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response,
Object handler,
Exception ex) throws Exception
{
//Transaction commit/rollback
if (null != session && session.isOpen())
{
try
{
session.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
In applicationContext.xml I defined the interceptor in this way:
<mvc:interceptors>
<bean class="com.interceptor.ControllerInterceptor" />
</mvc:interceptors>
My ControllerInterceptor is singleton but I need it in request scope. I tried to define the interceptor in this way:
<mvc:interceptors>
<bean class="com.interceptor.ControllerInterceptor" scope="request" />
</mvc:interceptors>
but I had this error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0': Initialization of bean failed; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
Any suggestion?Thanks