I am learning how to use the Spring framework to manage sleep mode transactions, and so far it has been a big help for this purpose. The problem is that lately I realized that I didn’t think about how the template that I selected handles concurrency, especially in the case of a web application.
Below is the code that illustrates the template I am using, which is a combination of some examples I found and a custom servlet implementation. I have a few doubts about how this template works and whether it is thread safe since I configured it a bit. Some of my problems are:
- Despite the fact that servlets are not technically single, I get the impression that in most cases there will be only one instance for each servlet class.
- If I understand correctly, each property with automatic wiring will be single-line, so if its value above is true, then there will be one instance of the servlet with one instance of the service, which, in turn, has one instance of the DAO, which has its own instance of SessionFactory.
- If this is correct, I can imagine that each request to the servlet will use the same objects, and I wonder if this is good. After I thought, I can’t say it would be better if the threading security was single-ended or created new instances for each HTTP request.
- Typically, these Spring templates have the @Controller class, which I skipped in favor of our custom servlet, and I wonder if this might somehow break the concurrency of the template.
thank
public interface UserDAO
{
public void save(User user);
}
@Repository
public class HibernateUserDAO implements UserDAO
{
@Autowired(required=true)
protected SessionFactory sessionFactory;
public void save(User user)
{
this.sessionFactory.getCurrentSession().save(user);
}
}
public interface UserService
{
public void saveUser(User user);
}
@Service
public class DefaultUserService implements UserService
{
@Autowired(required=true)
private UserDAO userDAO;
@Transactional
public void saveUser(User user)
{
this.userDAO.save(user);
}
}
public class UserServlet extends CustomServlet
{
@Autowired(required=true)
private UserService userService;
public void init() throws ServletException
{
super.init();
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
this.userService.saveUser(user);
}
}
source
share