0

I would like to use the Spring framework's JdbcTemplate inside my Java servlet. I have some jdbc configuration set up as a Java class and I'm wondering the correct way to load it and use it in the servlet. Where is the best place to put this code:

ApplicationContext ctx = new AnnotationConfigApplicationContext(JdbcConfig.class);

Should I create this ApplicationContext object on every doGet or doPost method? Or would it be better to create it once as a global variable?

public class MyServlet extends HttpServlet {

    // Should it go here as a global variable?

    public void doGet(HttpServletRequest req, HttpServletResponse resp) {
        // Or Here?
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) {
        // Or here?
    }
}

I ask because it seems like the jdbc configuration isn't changing, it loads when the servlet is created and then I just want to use it. At the same time, I don't know how safe that is. What if two users load the servlet at the same time, if the ApplicationContext is global, would that cause any problems with their queries running at the same time? Typically, I avoid global variables in servlets for reasons like that.

Or, is loading an ApplicationContext not a big deal to do on every single request?

Basically, I'm wondering what happens to the JdbcConfig and ApplicationContext objects if it is loaded once when the servlet starts. Does it basically become a "static" object? Would that have a negative effect?

Note, I'm not using Spring MVC or Spring Boot, just a plain Java servlet.

Edit: My question is a how and why, I want to understand, not just troubleshoot like the linked question.

jabe
  • 784
  • 2
  • 15
  • 33

0 Answers0