Spring入門Blog[十、Spring DBCP用xml和properties2種格式配置DataSource] – JAVA編程語言程序開發技術文章

 

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

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。