E
E
EgorSvinarev2020-08-14 20:12:10
Java
EgorSvinarev, 2020-08-14 20:12:10

How to use CDI to inject a type returned from a method?

Hello. There are several types:
1) ConnectionPool - the type responsible for obtaining Connection objects with the database. Its object is initialized and stored in the ServletContext.

public class ConnectionPool {

  @Inject
  private DataSource dataSource;
  private Stack<Connection> pool;
  
  public ConnectionPool() {
    this.pool = new Stack<Connection>(); 
  }

  public DataSource getDataSource() {
    return dataSource;
  }

  public void setDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
    
    this.closeAllConnections();	
  }
  
  private synchronized void openNewConnections() {
    if (dataSource != null) {
      for (int i = 0; i < 10; i++) {
        pool.add(dataSource.getConnection());
      }
    }
  }
  
  private synchronized void closeAllConnections() {
    for (int i = 0; i < pool.size(); i++) {
      Connection connection = pool.pop();
      try{
        connection.close();
      }
      catch (Exception ex) {
        System.out.println(ex);
      }
    }
  }
  
  public synchronized Connection takeConnection() {
    if (this.pool.size() < 2) {
      this.openNewConnections();
    }
    return this.pool.pop(); 
  }
  
  public synchronized void putConnection(Connection connection) {
    this.pool.add(connection);
  }	
}

2) DAO is a type that works directly with the database. This is where dependency injection takes place - an object of type Connection.
public class EmailDAO {

  @Inject
  private Connection Connection

}


Question: How can I resolve this dependency? i.e. in essence Connection, objects of type obtained from a method ConnectionPoolmust be injected into objects of type DAO, and how do I get the Weld container to resolve the dependency using objects returned from methods?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Ruslan., 2020-08-14
@LaRN

Perhaps here it is worth injecting a ConnectionPool object into EmailDAO
and creating a private getConnection method in EmailDAO, which will
receive a connection through the ConnectionPool and store it in the Connection field. Having a link to the ConnectionPool in EmailDAO, before destroying the EmailDAO object, it will be possible to return an already unnecessary Connection to the pool through the putConnection method and thereby save a valuable resource.
Well, or the second option is to create an intermediate object, which in its constructor will receive Connection from the ConnectionPool and inject this intermediate object into EmailDAO.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question