前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >【旧】G004Spring学习笔记-IOC案例

【旧】G004Spring学习笔记-IOC案例

作者头像
訾博ZiBo
发布2025-01-06 15:08:51
发布2025-01-06 15:08:51
8300
代码可运行
举报
运行总次数:0
代码可运行

一、XML方式实现

1、数据库创建语句

代码语言:javascript
代码运行次数:0
运行
复制
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文件

代码语言:javascript
代码运行次数:0
运行
复制
<?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文件

代码语言:javascript
代码运行次数:0
运行
复制
<?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

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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

代码语言:javascript
代码运行次数:0
运行
复制
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文件:
代码语言:javascript
代码运行次数:0
运行
复制
<?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:
代码语言:javascript
代码运行次数:0
运行
复制
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:
代码语言:javascript
代码运行次数:0
运行
复制
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);
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2025-01-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、XML方式实现
    • 1、数据库创建语句
    • 2、pom.xml文件
    • 3、bean.xml文件
    • 4、接口IAccountDao
    • 5、接口实现类AccountDaoImpl
    • 6、接口IAccountService
    • 7、接口实现类AccountServiceImpl
    • 8、实体类Account
    • 9、测试类AccountServiceTest
  • 二、注解方式实现
    • 1、说明
    • 2、代码
      • bean.xml文件:
      • 接口实现类AccountServiceImpl:
      • 接口实现类AccountDaoImpl:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档