Configurar un DataSource: DBCP

2343 vistas

Veamos un ejemplo de configuración de un DataSource con el API DBCP. Para este ejemplo usaremos JNDI pero podemos usar directamente la implementación (BasicDataSource).



java
  1. // inicialización del contexto
  2. System.setProperty(Context.INITIAL_CONTEXT_FACTORY,
  3.       "com.sun.jndi.fscontext.RefFSContextFactory");
  4.  
  5. // creación de una referencia al DataSource
  6. Reference ref = new Reference("javax.sql.DataSource",
  7.       "org.apache.commons.dbcp.BasicDataSourceFactory",
  8.       null);
  9. ref.add(new StringRefAddr("driverClassName", "com.mysql.jdbc.Driver"));
  10. ref.add(new StringRefAddr("url", "jdbc:mysql://localhost/mabase"));
  11. ref.add(new StringRefAddr("username", "xxx"));
  12. ref.add(new StringRefAddr("password", "xxx"));
  13.  
  14. // relacionamos el DataSource al contexto
  15. ic.rebind("jdbc/MaDataSource", ref);



Una vez creado el enlace, sólo nos queda recuperar el DataSource asÃ:



java
  1. // recuperamos el DataSource a partir del contexto
  2. Context ctx = new InitialContext();
  3. DataSource source = (DataSource)ctx.lookup("jdbc/MaDataSource");
  4.  
  5. // recuperación de una Connection
  6. Connection connection = source.getConnection();
  7. //...



Podemos encontrar más ejemplos de uso de DBCP aquÃ: