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

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

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

一、XML方式实现

1、数据库创建语句

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
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
运行
AI代码解释
复制
<?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
运行
AI代码解释
复制
<?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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
<?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
运行
AI代码解释
复制
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
运行
AI代码解释
复制
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 删除。

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

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Spring学习笔记(二)——依赖注入
依赖注入:Dependency Injection。它是 spring 框架核心 ioc 的具体实现。 我们的程序在编写时,通过控制反转,把对象的创建交给了 spring,但是代码中不可能出现没有依赖的情况。 ioc 解耦只是降低他们的依赖关系,但不会消除。例如:我们的业务层仍会调用持久层的方法。 那这种业务层和持久层的依赖关系,在使用 spring 之后,就让 spring 来维护了。 简单的说,就是坐等框架把持久层对象传入业务层,而不用我们自己去获取。
不愿意做鱼的小鲸鱼
2022/09/24
3140
快速学习-使用 spring 的 IoC 的实现账户的CRUD
使用 spring 的 IoC 实现对象的管理 使用 DBAssit 作为持久层解决方案 使用 c3p0 数据源
cwl_java
2020/04/02
4120
【旧】G006Spring学习笔记-IOC案例完善
訾博ZiBo
2025/01/06
510
【旧】G006Spring学习笔记-IOC案例完善
使用 spring 的 IoC 实现账户的 CRUD
大致步骤: 1.创建数据库 2.账户实体类 3.编写持久层代码 4.账户的持久层实现类 5.编写业务层代码 6.业务层实现类 7.配置文件 基本结构 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) value
别团等shy哥发育
2023/02/27
2160
使用 spring 的 IoC 实现账户的 CRUD
Spring Bean.xml配置c3p0数据库连接池
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
5860
基于Spring的转账事务管理
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
4160
Spring学习笔记(五)——JdbcTemplate和spring中声明式事务
它是 spring 框架中提供的一个对象,是对原始 Jdbc API 对象的简单封装。spring 框架为我们提供了很多的操作模板类。 1. 操作关系型数据的: JdbcTemplate HibernateTemplate 2. 操作 nosql 数据库的: RedisTemplate 3. 操作消息队列的: JmsTemplate spring中的JdbcTemplate在 spring-jdbc-5.0.2.RELEASE.jar 中,我们在导包的时候,除了要导入这个 jar 包外,还需要导入一个 spring-tx-5.0.2.RELEASE.jar(它是和事务相关的)。
不愿意做鱼的小鲸鱼
2022/09/24
1.2K0
Spring学习笔记(五)——JdbcTemplate和spring中声明式事务
Spring 基于注解配置方式的声明事务控制(注解方式)
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
8570
使用Spring编程式事务TransactionTemplate
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
4.2K0
【旧】G005Spring学习笔记-Spring完全注解实现及优化
因为junit继承了一个main方法,这个main方法会判断当前测试类中有@Test注解的方法,并使其执行;
訾博ZiBo
2025/01/06
950
【旧】G005Spring学习笔记-Spring完全注解实现及优化
Spring 通过单表 CURD 认识配置IOC的两兄弟(XML&注解)
前面一篇文章花大量内容,重点学习了 Spring入门 的一些思想,以及简单的学习了 IOC基础 以及基于基于 XML 的配置方式,大家应该清楚,XML与注解常常是形影不离的,他们就像一对双胞胎,但兄弟两个的想法都是一致的,那就是帮助开发者实现想要的功能,我们所说的IOC 技术,无疑是为了降低程序间的耦合,那么,今天就来聊一聊,基于注解的IOC配置,当然为了大家有对比学习,两种配置同时讲解,同时我把例举得尽量完整一些,就来完成一个对单表进行 CURD 的案例
BWH_Steven
2020/03/04
6290
【旧】G003Spring学习笔记-IOC之注解方式实现
属性:value用于指定bean的id,当我们不写时,默认为当前类名,首字母小写;
訾博ZiBo
2025/01/06
720
【旧】G003Spring学习笔记-IOC之注解方式实现
【旧】G002Spring学习笔记-IOC之XML方式实现
它在构建容器时,创建对象采用的策略是立即加载的方式,也就是说,一读完配置文件就马上创建对象;
訾博ZiBo
2025/01/06
780
【旧】G002Spring学习笔记-IOC之XML方式实现
Spring 基于xml的ioc案例 搭建spring开发环境思路分析
基于xml的ioc案例 结构图 一、pom.xml导坐标 <packaging>jar</packaging> <dependencies> <!--spring的坐标--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.0.2.R
韦恩少爷的背
2020/03/19
3280
Spring的两大核心IOC和AOP
IOC全称Inverse Of Control,中文名控制反转,是spring框架中一种降低程序耦合度(降低程序依赖关系)的设计思想。它的主要目的就是将对象的创建控制权完全交给spring提供的容器处理,由容器统一创建,调用方只需关注对象实现的功能,而无需关注对象是如何创建的。
兜兜转转
2023/03/08
8960
Spring的两大核心IOC和AOP
Spring JdbcTemplate 使用及持久层继承JdbcDaoSupport XML配置
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
多凡
2019/11/01
4120
从零开始重新认识 Spring Framework
如果你想快速入门 Spring 框架,或者想快速复习 Spring 的基本操作,那么这篇文章再适合你不过了。
wsuo
2020/07/30
4960
从零开始重新认识 Spring Framework
快速学习-AOP 的相关概念
作用: 在程序运行期间,不修改源码对已有方法进行增强。 优势: 减少重复代码 提高开发效率 维护方便
cwl_java
2020/04/02
3450
快速学习-SSM 整合
持久层实现类代码: 此时不要做任何操作,就输出一句话。目的是测试 spring 框架搭建的结果。
cwl_java
2020/04/08
5040
SSH框架之Spring第四篇
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
海仔
2019/09/23
5370
推荐阅读
相关推荐
Spring学习笔记(二)——依赖注入
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验