G004Spring學習筆記-IOC案例

一、XML方式實現

1、數據庫創建語句

create table account(
	id int primary key auto_increment,
	name varchar(40),
	money float
)character set utf8 collate utf8_general_ci;

insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);

2、pom.xml文件

<?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>org.example</groupId>
    <artifactId>spring05</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.19</version>
        </dependency>
        <dependency>
            <groupId>commons-dbutils</groupId>
            <artifactId>commons-dbutils</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13-beta-3</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

3、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.zibo.service.impl.AccountServiceImpl">
        <!--注入dao-->
        <property name="accountDao" ref="accountDao"/>
    </bean>
    <!--配置Dao-->
    <bean id="accountDao" class="com.zibo.dao.impl.AccountDaoImpl">
        <!--注入QueryRunner-->
        <property name="runner" ref="runner"/>
    </bean>
    <!--配置QueryRunner,多例-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入數據源-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
    <!--配置數據源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入連接數據庫的信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/zibo?serverTimezone=UTC"/>
        <property name="user" value="***************"/>
        <property name="password" value="***************"/>
    </bean>
</beans>

4、接口IAccountDao

package com.zibo.dao;

import com.zibo.domain.Account;

import java.util.List;

public interface IAccountDao {
    //查詢所有賬戶
    List<Account> findAllAccount();
    //根據id查詢賬戶
    Account findAccountById(Integer accountId);
    //保存賬戶
    void saveAccount(Account account);
    //更新賬戶
    void updateAccount(Account account);
    //刪除用戶
    void deleteAccountById(Integer accountId);
}

5、接口實現類AccountDaoImpl

package com.zibo.dao.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.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;

/**
 * 賬戶的持久層實現類
 */

public class AccountDaoImpl implements IAccountDao {

    private QueryRunner runner;

    public void setRunner(QueryRunner runner) {
        this.runner = runner;
    }

    @Override
    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<>(Account.class));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?",new BeanHandler<>(Account.class),accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    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);
        }
    }

    @Override
    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);
        }
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        try {
            runner.update("delete from account where id = ?",accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

6、接口IAccountService

package com.zibo.service;

import com.zibo.domain.Account;

import java.util.List;

/**
 *  賬戶的業務層接口
 */
public interface IAccountService {
    //查詢所有賬戶
    List<Account> findAllAccount();
    //根據id查詢賬戶
    Account findAccountById(Integer accountId);
    //保存賬戶
    void saveAccount(Account account);
    //更新賬戶
    void updateAccount(Account account);
    //刪除用戶
    void deleteAccountById(Integer accountId);
}

7、接口實現類AccountServiceImpl

package com.zibo.service.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.domain.Account;
import com.zibo.service.IAccountService;

import java.util.List;

public class AccountServiceImpl implements IAccountService {

    private IAccountDao accountDao;

    public void setAccountDao(IAccountDao accountDao) {
        this.accountDao = accountDao;
    }

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        accountDao.deleteAccountById(accountId);
    }
}

8、實體類Account

package com.zibo.domain;

import java.io.Serializable;

public class Account implements Serializable {
    private Integer id;
    private String name;
    private float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getMoney() {
        return money;
    }

    public void setMoney(float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

9、測試類AccountServiceTest

package com.zibo.test;

import com.zibo.domain.Account;
import com.zibo.service.IAccountService;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;

/**
 * 使用junit單元測試進行測試
 */
public class AccountServiceTest {
    private ClassPathXmlApplicationContext ac;
    private IAccountService as;
    @Before
    public void init(){
        //1、獲取容器
        ac = new ClassPathXmlApplicationContext("bean.xml");
        //2、得到業務層對象
        as = ac.getBean("accountService",IAccountService.class);
    }
    @Before
    public void end(){
        ac.close();
    }
    @Test
    public void testFindAllAccount(){
        //3、執行方法
        List<Account> accounts = as.findAllAccount();
        //4、遍歷輸出
        for (Account account : accounts) {
            System.out.println(account);
        }
    }
    @Test
    public void testFindAccountById(){
        Account account = as.findAccountById(1);
        System.out.println(account);
    }
    @Test
    public void testSave(){
        Account account = new Account();
        account.setName("大哥");
        account.setMoney(2000);
        as.saveAccount(account);
    }
    @Test
    public void testUpdate(){
        Account account = new Account();
        account.setId(3);
        account.setName("二哥");
        account.setMoney(3000);
        as.updateAccount(account);
    }
    @Test
    public void testDelete(){
        as.deleteAccountById(1);
    }
}

 

二、註解方式實現

1、說明

目前的註解方式只需要對XML稍作修改,下面把更改的代碼貼出來,其餘代碼見上面;

 

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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">
    <!--告訴spring要創建容器時要掃描的包,但是配置所需要的標籤不在<beans/>標籤中,
        而是一個名稱爲context的名稱空間和約束中-->
    <context:component-scan base-package="com.zibo"/>
    <!--配置QueryRunner,多例-->
    <bean id="runner" class="org.apache.commons.dbutils.QueryRunner" scope="prototype">
        <!--注入數據源-->
        <constructor-arg name="ds" ref="dataSource"/>
    </bean>
    <!--配置數據源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!--注入連接數據庫的信息-->
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/zibo?serverTimezone=UTC"/>
        <property name="user" value="***************"/>
        <property name="password" value="***************"/>
    </bean>
</beans>

接口實現類AccountServiceImpl:

package com.zibo.service.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.domain.Account;
import com.zibo.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 賬戶的業務層實現類
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private IAccountDao accountDao;

    @Override
    public List<Account> findAllAccount() {
        return accountDao.findAllAccount();
    }

    @Override
    public Account findAccountById(Integer accountId) {
        return accountDao.findAccountById(accountId);
    }

    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
    }

    @Override
    public void updateAccount(Account account) {
        accountDao.updateAccount(account);
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        accountDao.deleteAccountById(accountId);
    }
}

接口實現類AccountDaoImpl:

package com.zibo.dao.impl;

import com.zibo.dao.IAccountDao;
import com.zibo.domain.Account;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 賬戶的持久層實現類
 */
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
    @Autowired
    private QueryRunner runner;

    @Override
    public List<Account> findAllAccount() {
        try {
            return runner.query("select * from account",new BeanListHandler<>(Account.class));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public Account findAccountById(Integer accountId) {
        try {
            return runner.query("select * from account where id = ?",new BeanHandler<>(Account.class),accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    @Override
    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);
        }
    }

    @Override
    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);
        }
    }

    @Override
    public void deleteAccountById(Integer accountId) {
        try {
            runner.update("delete from account where id = ?",accountId);
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}

 

 

 

 

 

 

 

 

發佈了143 篇原創文章 · 獲贊 24 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章