Spring provides database connection pooling: Dbcp configures DataSource and obtains connection completion database operations: Address of the Spring Help document: http://static.springsource.org/spring/docs/2.5.6/ reference/beans.html# Beans-value-element the jar package that needs to be imported: Commons-dbcp.jarcommons-pool.jarmysql-connector-java-5.0-nightly-20071116-bin.jar 1. First configure the data source within the container [HTML] View plain copy
- <!--configuring data sources-
- <bean id= "myDataSource" class= "Org.apache.commons.dbcp.BasicDataSource" destroy-method= "Close" >
- <property name= "Driverclassname" value= "Com.mysql.jdbc.Driver"/>
- <property name= "url" value= "Jdbc:mysql://localhost:3306/sms"/>
- <property name= "username" value= "root"/>
- <property name= "Password" value= "root"/>
- </bean>
2. Get the injected data source and write operations on the database [Java] View plain copy
- @Component ("UserService")
- public class Userserviceimpl implements userservice{
- Private Userdao Userdao;
- public void Setuserdao (Userdao Userdao) {
- This.userdao = Userdao;
- }
- @Resource//resource Injection
- Private DataSource myDataSource;
- Public DataSource Getmydatasource () {
- return mydatasource;
- }
- public void Setmydatasource (DataSource mydatasource) {
- This.mydatasource = myDataSource;
- }
- In the preceding method, add the logical
- public void Save () {
- try{
- Get the connection to perform the operation
- Connection conn = Mydatasource.getconnection ();
- Conn.createstatement (). Execute ("INSERT INTO dept values (' 6 ', ' Bumen2 ')");
- }catch (Exception e) {
- E.printstacktrace ();
- }
- }
- }
3. Test run [Java] View plain copy
- @Test
- public void test01 () {
- Beanfactory ApplicationContext = new Classpathxmlapplicationcontext (
- "Beans.xml");
- UserService user = (UserService) applicationcontext.getbean ("UserService");
- User.save ();
- }
--------------------------------------------------------------------------------------------------------------- -------------------Configure the Datasource:1 of XML by the properties, write the properties file: [HTML] View plain copy
- Jdbc.driverclassname=com.mysql.jdbc.driver
- Jdbc.url=jdbc:mysql://localhost:3306/sms
- Jdbc.username=root
- Jdbc.password=root
2. Writing XML container configuration: [HTML] View plain copy
- <!--placeholder Placeholder--
- <bean
- class= "Org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
- <property name= "Locations" >
- <value>classpath:jdbc.properties</value>
- </property>
- </bean>
- <bean id= "DataSource" destroy-method= "Close"
- class= "Org.apache.commons.dbcp.BasicDataSource" >
- <property name= "Driverclassname" value= "${jdbc.driverclassname}"/>
- <property name= "url" value= "${jdbc.url}"/>
- <property name= "username" value= "${jdbc.username}"/>
- <property name= "Password" value= "${jdbc.password}"/>
- </bean>
Spring DBCP is configured in XML and Properties2 formats DataSource