SSH框架搭建过程---之Spring框架的使用(2)

Spring框架的使用

1.  导包

2.  bean.xml

<?xml version="1.0"encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
</beans>



1)   配置dataSource

     

  <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<propertyname="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"value="jdbc:mysql://localhost:3306/graduate" />
           <propertyname="username" value="root" />
           <propertyname="password" value="root" />
       </bean>

2)   配置JdbcTemplate

<bean id="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">
           <propertyname="dataSource" ref="dataSource" />
    </bean>


3.  编写DAO组件

private final String SQL = “insert into Demo values(?, ?, ?)”;
private JdbcTemplate jdbcTemplate;
 
public void setJdbcTemplate(JdbcTemplate jdbcTemplate){
    this.jdbcTemplate = jdbcTemplate;
}
    /**
     * 此方法是用了Spring
     * @param demo
     * @throws DemoException
     */
    public void saveDemo(Demo demo) throws DemoException {
       try{
jdbcTemplate.update(SQL, new Object[]{0, demo.getName(), demo.getPassword()});
       } catch(DataAccessException e){
           throw new DemoException("保存信息出错。");
       }
    }


 

4.  添加

<bean id="demoDAO" class="cn.edu.bucea.DAO.DemoDAO">
    <property name="jdbcTemplate"ref="jdbcTemplate" />
</bean>


注:此时即实现了Spring提供了JdbcTemplate访问数据库。

5.  实现Spring服务组件


 

import cn.edu.bucea.DAO.DemoDAO;
import cn.edu.bucea.domain.Demo;
import cn.edu.bucea.exception.DemoException;
 
public class DemoService {
    private DemoDAO demoDAO;
 
    public void setDemoDAo(DemoDAO demoDAO) {
       this.demoDAO = demoDAO;
    }
   
    public void createDemo(Demo demo) throws DemoException {
       demoDAO.saveDemo(demo);
    }
}

6.  添加

<bean id="demoService"class="cn.edu.bucea.service.DemoService">
    <property name="demoDAO" ref="demoDAO"/>
</bean>


接下来在DemoService中注入DAO组件。

注:以上是Spring框架的单独应用

=======================================================================================

下一篇:SSH框架搭建过程---之Struts框架的使用


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值