Spring入门Blog[十、Spring DBCP用xml和properties2种格式配置DataSource]
1. 首先在容器内配置数据源
[html]
<!-- 配置数据源 -->
<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.拿到注入数据源并且编写对数据库的操作
[java]
@Component("userService")
public class UserServiceImpl implements UserService{
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Resource //resource注入
private DataSource myDataSource;
public DataSource getMyDataSource() {
return myDataSource;
}
public void setMyDataSource(DataSource myDataSource) {
this.myDataSource = myDataSource;
}
//在下面方法前面加逻辑
public void save(){
try{
//拿到连接执行操作
Connection conn = myDataSource.getConnection();
conn.createStatement().execute("insert into dept values('6','bumen2')");
}catch(Exception e){
e.printStackTrace();
}
}
}
3.测试运行
[java]
@Test
public void test01() {
BeanFactory applicationContext = new ClassPathXmlApplicationContext(
"beans.xml");
UserService user = (UserService) applicationContext.getBean("userService");
user.save();
}
----------------------------------------------------------------------------------------------------------------------------------通过Properties的方式配置xml的datasource:
1、 编写properties文件:
[html]
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sms
jdbc.username=root
jdbc.password=root
2、编写xml容器配置:
[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>
作者:zhang6622056
补充:软件开发 , Java ,