Pavel
Pavel

Reputation: 2101

How to do dependencies injection in class servlet?

I have two servlets, and both use same object for work with database. But using constructor or setter for injection reference to object impossible. Help me please, how to do this in my case:

First Servlet:

public class AddUserServlet extends HttpServlet {

    private DBJointPool db; // Как передать этот объект в класс?

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        db.somethingToDoWithDatabaseConnectionPool();

    }
}

Second Servlet:

public class DeleteUserServlet extends HttpServlet {

    private DBJointPool db; // Как передать этот объект в класс?

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        db.somethingToDoWithDatabaseConnectionPool();

    }
}

I use JDBC driver without framework.

Upvotes: 1

Views: 961

Answers (1)

Horsing
Horsing

Reputation: 1100

If spring-boot is included in your project, here would be the solution for your requirement:

@Bean
public ServletRegistrationBean addUserServlet(DBJointPool db) {
    // suppose there is a constructor for your servlet
    final ServletRegistrationBean servlet = new ServletRegistrationBean(new AddUserServlet(db));
    servlet.setName("addUserServlet");
    servlet.setUrlMappings(Collections.singletonList("/addUser.*"));
    return servlet;
}

And expose DeleteUserServlet as following:

@Bean
public ServletRegistrationBean deleteUserServlet(DBJointPool db) {
    // suppose there is a constructor for your servlet
    final ServletRegistrationBean servlet = new ServletRegistrationBean(new DeleteUserServlet(db));
    servlet.setName("deleteUserServlet");
    servlet.setUrlMappings(Collections.singletonList("/deleteUser.*"));
    return servlet;
}

Of course, you have to expose DBJointPool somewhere else, for example:

@Bean
public DBJointPool dBJointPool() {
    return new DBJointPool();
}

However, if you are not using spring-boot but spring framework is acceptable, then configure these beans in application context xml file would also work.

At last, if spring is not acceptable, please consider singletons, such as static member for these instances.

Please let me know if any problems.

Upvotes: 1

Related Questions