1. First configure the data source in the container
[Html]
<! -- Configure the data source -->
<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 injection data source and write operations on the database
[Java]
@ 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;
}
// Add logic before the following method
Public void save (){
Try {
// Get the connection and perform the operation
Connection conn = myDataSource. getConnection ();
Conn.createstatement(cmd.exe cute ("insert into dept values ('6', 'bumen2 ')");
} Catch (Exception e ){
E. printStackTrace ();
}
}
}
3. Test Run
[Java]
@ Test
Public void test01 (){
BeanFactory applicationContext = new ClassPathXmlApplicationContext (
"Beans. xml ");
UserService user = (UserService) applicationContext. getBean ("userService ");
User. save ();
}
Dependencies --- configure the xml datasource through Properties:
1. Compile the properties file:
[Html]
Jdbc. driverClassName = com. mysql. jdbc. Driver
Jdbc. url = jdbc: mysql: // localhost: 3306/sms
Jdbc. username = root
Jdbc. password = root
2. Compile xml container Configuration:
[Html] view plaincopy
<! -- 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>
Author: zhang6622056