package app10e.util; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; import app10d.action.GetProductsAction; import app10d.action.SaveProductAction; import app10d.dao.ProductDAO; import app10d.dao.ProductDAOImpl; import app10d.validator.ProductValidator; public class DependencyInjector { private DataSource dataSource; public void start() { //使用C3P0连接池 ComboPooledDataSource cpds=new ComboPooledDataSource(); try { cpds.setDriverClass("com.mysql.jdbc.Driver"); } catch(Exception e) { e.printStackTrace(); } cpds.setJdbcUrl("jdbc:mysql://localhost:3306/test"); cpds.setUser("root"); cpds.setPassword("123"); cpds.setMinPoolSize(5); cpds.setAcquireIncrement(5); cpds.setMaxPoolSize(20); dataSource=cpds; } public void shutDown() { try { DataSources.destroy(dataSource); } catch(Exception e) { e.printStackTrace(); } } public Object getObject(Class type) { if(type==ProductValidator.class) { return new ProductValidator(); } else if(type==ProductDAO.class) { return createProductDAO(); } else if(type==GetProductsAction.class) { return createGetProductAction(); } else if(type==SaveProductAction.class) { return createSaveProductAction(); } return null; } private GetProductsAction createGetProductAction() { GetProductsAction getProductsAction=new GetProductsAction(); getProductsAction.setProductDAO(createProductDAO()); return getProductsAction; } private SaveProductAction createSaveProductAction() { SaveProductAction saveProductAction=new SaveProductAction(); saveProductAction.setProductDAO(createProductDAO()); return saveProductAction; } private ProductDAO createProductDAO() { ProductDAO productDAO=new ProductDAOImpl(); productDAO.setDataSource(dataSource); return productDAO; } }
时间: 2025-01-04 19:18:45