zl程序教程

您现在的位置是:首页 >  其他

当前栏目

基于XML的IOC的案例

案例XML 基于 IOC
2023-09-27 14:19:50 时间

基于XML的IOC的案例
1 基于XML的IOC的案例准备
1.打开IDEA工具如图所示的界面,点击Create New Project。在这里插入图片描述
2.选择Maven工程和JDK的版本,如图所示:并点击Next。在这里插入图片描述
3.填写项目名称和保存的地址,点击Finish。如图所示:在这里插入图片描述
4.导入相应的依赖jar包的代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.txw</groupId>
    <artifactId>springy_02account_xmlioc</artifactId>
    <version>1.0-SNAPSHOT</version>
    <!--打包的方式 -->
    <packaging>jar</packaging>
    <dependencies>
        <!--导入spring-context的依赖jar包坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--导入lombok的依赖jar包坐标-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.12</version>
        </dependency>
        <!--导入mysql的依赖jar包坐标-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>6.0.6</version>
        </dependency>
        <!--导入commons-dbutils的依赖jar包坐标-->
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.7</version>
        </dependency>
        <!--导入spring-test的依赖jar包坐标-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>
        <!--导入c3p0的依赖jar包坐标-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <!--导入junit的依赖jar包坐标-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>
</project>

5.编写账户实体类的代码如下:

package com.txw.domain;

import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
 * 账户的实体类
 * @author:Adair
 * @QQ:1578533828
 */
@Data     // 自动生成set和get方法
@ToString // 重写toString方法
@SuppressWarnings("all")      // 注解警告信息
public class Account implements Serializable {
    private Integer id;      // 账户的id
    private String name;     // 账户的名称
    private Float money;     // 账户的金额
}

6.编写账户的业务层接口代码如下:

package com.txw.service;

import com.txw.domain.Account;
import java.util.List;
/**
 *账户的业务层接口
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public interface AccountService {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 根据id删除
     * @param acccountId
     */
    void deleteAccount(Integer accountId);
}

7.编写账户的业务层实现类代码如下:

package com.txw.service.impl;

import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import com.txw.service.AccountService;
import java.util.List;
/**
 * 账户的业务层实现类
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public class AccountServiceImpl implements AccountService {
    // 声明AccountDao业务对象
    private AccountDao accountDao;
    /**
     * set注入
     * @param accountDao
     */
    public void setAccountDao(AccountDao accountDao) {
        this.accountDao = accountDao;
    }
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }
    /**
     * 根据id查询一个
     * @return
     */
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }
    /**
     * 保存账户
     * @param account
     */
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }
    /**
     * 修改账户
     * @param account
     */
    public void updateAccount(Account account) {
    accountDao.updateAccount(account);
    }
    /**
     * 根据id删除
     * @param acccountId
     */
    public void deleteAccount(Integer accountId) {
        accountDao.deleteAccount(accountId);
    }
}

8.编写账户的持久层接口代码如下:

package com.txw.dao;

import com.txw.domain.Account;
import java.util.List;
/**
 * 账户的持久层接口
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public interface AccountDao {
    /**
     * 查询所有
     * @return
     */
    List<Account> findAllAccount();
    /**
     * 根据id查询一个
     * @return
     */
    Account findAccountById(Integer accountId);
    /**
     * 保存账户
     * @param account
     */
    void saveAccount(Account account);
    /**
     * 更新账户
     * @param account
     */
    void updateAccount(Account account);
    /**
     * 根据id删除
     * @param acccountId
     */
    void deleteAccount(Integer accountId);
}

9.编写账户的持久层实现类代码如下:

package com.txw.dao.impl;

import com.txw.dao.AccountDao;
import com.txw.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.util.List;
/**
 * 账户的持久层实现类
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
public class AccountDaoImpl implements AccountDao {
    // 声明QueryRunner业务对象
    private QueryRunner runner;
    /**
     * set注入
     * @param runner
     */
    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }
    /**
     * 查询所有
     * @return
     */
    public List<Account> findAllAccount() {
        try{
            return runner.query("select * from account",new BeanListHandler<Account>(Account.class));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据id查询一个
     * @return
     */
    public Account findAccountById(Integer accountId) {
        try{
            return runner.query("select * from account where id = ? ",new BeanHandler<Account>(Account.class),accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 保存账户
     * @param account
     */
    public void saveAccount(Account account) {
        try{
            runner.update("insert into account(name,money)values(?,?)",account.getName(),account.getMoney());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 修改账户
     * @param account
     */
    public void updateAccount(Account account) {
        try{
            runner.update("update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 根据id删除
     * @param accountId
     */
    public void deleteAccount(Integer accountId) {
        try{
            runner.update("delete from account where id=?",accountId);
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

2 基于XML的IOC的案例-编写spring的Ioc配置
1.在resources目录下创建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/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!-- 配置Service -->
    <bean id="accountService" class="com.txw.service.impl.AccountServiceImpl">
        <!-- 注入dao -->
        <property name="accountDao" ref="accountDao"></property>
    </bean>
    <!--配置Dao对象-->
    <bean id="accountDao" class="com.txw.dao.impl.AccountDaoImpl">
        <!-- 注入QueryRunner -->
        <property name="runner" ref="runner"></property>
    </bean>
    <!--配置QueryRunner-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入数据源-->
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--连接数据库的必备信息-->
        <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring?useUnicode=true&amp;characterEncoding=utf8&amp;serverTimezone=UTC&amp;useSSL=false"/>
        <property name="user" value="root"></property>
        <property name="password" value="123456"></property>
    </bean>
</beans>

2.编写测试的代码如下:

package com.txw.test;

import com.txw.domain.Account;
import com.txw.service.AccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
/**
 * 使用Junit单元测试
 * @author:Adair
 * @QQ:1578533828
 */
@SuppressWarnings("all")      // 注解警告信息
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:bean.xml")
public class AccountServiceTest {
    // 声明AccountService业务对象
    @Autowired
    private AccountService as;
    /**
     * 测试查询所有
     */
    @Test
    public void testFindAll() {
        // 3.执行方法
        List<Account> accounts = as.findAllAccount();
        for(Account account : accounts){
            System.out.println(account);
        }
    }
    /**
     * 测试根据id查询一个
     */
    @Test
    public void testFindOne() {
        //3.执行方法
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    /**
     * 测试保存账户
     */
    @Test
    public void testSave() {
        Account account = new Account();
        account.setName("Adair");
        account.setMoney(12345f);
        //3.执行方法
        as.saveAccount(account);

    }
    /**
     * 测试修改账户
     */
    @Test
    public void testUpdate() {
        //3.执行方法
        Account account = as.findAccountById(4);
        account.setMoney(23456f);
        as.updateAccount(account);
    }
    /**
     * 测试根据id删除
     */
    @Test
    public void testDelete() {
        //3.执行方法
        as.deleteAccount(4);
    }
}