SpringIOC和SpringAOC

news2024/9/24 11:33:11
lombok插件
XML

    <!-- 加载资源文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 注入数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${msg1}"></property>
        <property name="jdbcUrl" value="${msg2}"></property>
        <property name="user" value="${msg3}"></property>
        <property name="password" value="${msg4}"></property>
    </bean>

    <!-- 注入QueryRunner -->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>

    <!-- 连接工具类 -->
    <bean id="connectionUtil" class="com.xn.util.ConnectionUtil">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 事务工具类 -->
    <bean id="transactionUtil" class="com.xn.util.TransactionUtil">
        <property name="connectionUtil" ref="connectionUtil"/>
    </bean>

    <!-- 注入dao -->
    <bean id="mapperImp" class="com.xn.dao.AccountMapperImp">
        <property name="queryRunner" ref="queryRunner"></property>
        <property name="connectionUtil" ref="connectionUtil"></property>
    </bean>

    <!-- 注入service -->
    <bean id="service" class="com.xn.service.AccountServiceImp">
        <property name="mapper" ref="mapperImp"/>
        <property name="transactionUtil" ref="transactionUtil"></property>
    </bean>

    <!-- 注入controller -->
    <bean id="controller" class="com.xn.controller.AccountControllerImp">
        <property name="service" ref="service"/>
    </bean>
功能:对实体类自动,动态生成getset,无参有参.....
步骤:
    1.idea安装插件(只做一次)


    2.添加坐标
     <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.26</version>
        </dependency>
    </dependencies>
   3.编写注解

dbUtil-阿帕奇提供操作数据库的插件
核心类:QueryRunner
            .query()  查询
            .update() 增删改

    //操作数据库的核心类
    QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }



@Override
    public void save(Account account) {
        try {
            queryRunner.update(connectionUtil.createCon(),"insert into account(aname,amoney) value(?,?)",account.getAname(),account.getAmoney());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }



@Override
    public void updateById(Account account) {
        try {
            queryRunner.update(connectionUtil.createCon(),"update  account set aname=?,amoney=? where aid=?",account.getAname(),account.getAmoney(),account.getAid());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    @Override
    public void deleteById(int id) {
        try {
            queryRunner.update(connectionUtil.createCon(),"delete from account where aid=?",id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
 <!-- 注入QueryRunner -->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>
junit测试
使用步骤:
    1.坐标
     单元测试-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
   2.注解(修饰方法)
        @Test======>可以运行的方法
        @Before====>@Test运行之前
        @After=====>@Test运行之后
public class Test01 {
    ClassPathXmlApplicationContext applicationContext=null;
    IAccountController controller=null;

    @Before
    public void beforeMethod(){
        applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
        controller = (IAccountController) applicationContext.getBean("controller");
    }


    @After
    public void afterMethod(){
        applicationContext.close();
    }


    @Test
    public void show1(){
        controller.save(new Account("林航宇",2000));
        controller.save(new Account("杨文琪",2000));
    }

    @Test
    public void show2(){
        List<Account> all = controller.findAll();
        for (int i = 0; i < all.size(); i++) {
            Account account =  all.get(i);
            System.out.println(account);
        }
    }

}

注解

 <!-- 加载资源文件 -->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!-- 注入数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${msg1}"></property>
        <property name="jdbcUrl" value="${msg2}"></property>
        <property name="user" value="${msg3}"></property>
        <property name="password" value="${msg4}"></property>
    </bean>

    <!-- 注入QueryRunner -->
    <bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
        <constructor-arg name="ds" ref="dataSource"></constructor-arg>
    </bean>


    <context:component-scan base-package="com.xn"></context:component-scan>
</beans>

配置工具

项目总结:
    1.事务管理应该由service层进行实现
代码优化:
    目的:业务层进行事务管理
public class AccountServiceImp implements IAccountService{

    IAccountMapper mapper;

    public void setMapper(IAccountMapper mapper) {
        this.mapper = mapper;
    }

    //装配
    TransactionUtil transactionUtil;

    public void setTransactionUtil(TransactionUtil transactionUtil) {
        this.transactionUtil = transactionUtil;
    }

    @Override
    public void transfer(String sourceName, String targetName, int money) {

        try {
            transactionUtil.beginTx();

            //查询数据
            Account sourceAccount=mapper.findByName(sourceName);
            Account targetAccount=mapper.findByName(targetName);

            //转账
            sourceAccount.setAmoney(sourceAccount.getAmoney()-money);
            targetAccount.setAmoney(targetAccount.getAmoney()+money);

            //修改数据库
            mapper.updateById(sourceAccount);
//            int a=10/0;//模拟异常
            mapper.updateById(targetAccount);

            transactionUtil.commitTx();

        } catch (Exception e) {
            e.printStackTrace();
            transactionUtil.rollbackTx();
        } finally {
            transactionUtil.closeTx();
        }
    }
    1.同一个业务方法的多个dao方法公用一个connection对象
public class AccountMapperImp implements IAccountMapper{

    //操作数据库的核心类
    QueryRunner queryRunner;

    public void setQueryRunner(QueryRunner queryRunner) {
        this.queryRunner = queryRunner;
    }

    //注入连接工具类
     ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }


    @Override
    public void save(Account account) {
        try {
            queryRunner.update(connectionUtil.createCon(),"insert into account(aname,amoney) value(?,?)",account.getAname(),account.getAmoney());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
   2.ThreadLocal
<!-- 事务工具类 -->
    <bean id="transactionUtil" class="com.xn.util.TransactionUtil">
        <property name="connectionUtil" ref="connectionUtil"/>
    </bean>

    <!-- 注入dao -->
    <bean id="mapperImp" class="com.xn.dao.AccountMapperImp">
        <property name="queryRunner" ref="queryRunner"></property>
        <property name="connectionUtil" ref="connectionUtil"></property>
    </bean>

    <!-- 注入service -->
    <bean id="service" class="com.xn.service.AccountServiceImp">
        <property name="mapper" ref="mapperImp"/>
        <property name="transactionUtil" ref="transactionUtil"></property>
    </bean>
    3.通过连接对象进行事务的统一管理
public class ConnectionUtil {
    //装配数据源
    DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    //线程区域对象
    ThreadLocal<Connection> threadLocal=new ThreadLocal<Connection>();

    //获取连接
    public Connection createCon(){

        try {
            //获取线程内的连接对象
            Connection connection=threadLocal.get();
            //判断
            if(connection==null){
                connection=dataSource.getConnection();//创建连接
                threadLocal.set(connection);//保存
            }
            return  connection;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return null;
    }

    //移除连接
    public void removeCon(){
        threadLocal.remove();//一处连接对象
    }
}
public class TransactionUtil {
    //注入连接工具类
    ConnectionUtil connectionUtil;

    public void setConnectionUtil(ConnectionUtil connectionUtil) {
        this.connectionUtil = connectionUtil;
    }

    //开启事务
    public void beginTx(){
        try {
            connectionUtil.createCon().setAutoCommit(false);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //提交事务
    public void commitTx(){
        try {
            connectionUtil.createCon().commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //回滚事务
    public void rollbackTx(){
        try {
            connectionUtil.createCon().rollback();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    //关闭事务
    public void closeTx(){
        try {
            connectionUtil.createCon().close();
            connectionUtil.removeCon();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2033736.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Supervision 计算机视觉工具

简介 Supervision库是Python计算机视觉低代码工具&#xff0c;旨在为用户提供便捷高效的接口&#xff0c;以便处理数据集并直观地展示检测结果。绘制检测结果&#xff0c;统计指定区域内检测目标数量Supervision都提供了相应的接口 安装库 要求Python版本>3.8 1.安装无图像…

【机器学习】反向传播算法的直观解释、微积分原理以及反向传播中的链式法则

引言 正如有句话说的好&#xff0c;neurons-that-fire-together-wire-together&#xff08;一同激活的神经元关联在一起&#xff09; 文章目录 引言一、反向传播算法的直观解释1.1 前向传播1.2 计算误差1.3 反向传播误差1.4 更新权重 二、微积分原理2.1 损失函数 L L L2.2 链式…

javaEE WebServlet、SpringWebMVC、SpringBoot实现跨域访问的4种方式及优先级

文章目录 1. 前置知识2. 原理和解决方案总结2.1. 跨域不通过原理流程图2.2. 实现原理&#xff1a;添加以下http响应头2.3. 四种跨域实现方式及优先级&#xff08;从高到低&#xff09; 3. 具体实现代码3.1. 跨域全局配置方式-Filter(全适用)3.2. 跨域全局配置方式-SpringMvc3.3…

数字孪生模型制作教程虚拟现实城市模型制作3dmax数字城市glb/gltf

需要做数字孪生可以QQ可以联系这里&#xff0c;谢谢 下面开始教程 1打开3dmax软件&#xff0c;和需要做的建筑图片 2 在3dmax安图片先建一个长方体框架 3先给长方体贴一个墙体贴图 4在ps做贴图 5 做好贴图贴到3dmax中 6 然后ps再做下一张贴图 7 做好贴图贴到3dma…

[Redis] Redisson分布式锁原理及源码分析

目录 基于 Redis 的分布式锁 Redisson实现分布 Redisson分布式锁原理图 RedissonLock实现分布式锁源码分析 RedissonLock构造方法 lock()加锁 获取锁 锁续命逻辑 tryLockInnerAsync加锁lua脚本分析 unlock()解锁 基于 Redis 的分布式锁 实现方式: 使用 Redis 的 SE…

Idea2023.3版本创建spring Initializr没有JDK8

解决方法&#xff1a; https://start.aliyun.com

SOMEIP_ETS_037:echoUINT8RELIABLE_client_closes_TCP_connection_automatically

测试目的&#xff1a; 验证当所有服务停止时&#xff0c;DUT不会关闭TCP连接。 描述 本测试用例旨在检验DUT在停止所有服务时&#xff0c;是否能够保持TCP连接的活跃状态&#xff0c;而不发送FIN,ACK以关闭连接。 测试拓扑&#xff1a; 具体步骤&#xff1a; TESTER&#…

STM32学习笔记3 ---中断,定时器

目录 EXTI外部中断 NVIC嵌套中断向量控制器 EXTI外部中断 AFIO 旋转编码器 定时器TIM TIM定时中断 ​编辑​编辑 ​编辑 TIM输出比较&#xff08;OC&#xff09; 引脚重映射 舵机 直流电机 TIM输入捕获&#xff08;IC&#xff09; ​编辑 TIM编码器接口 附&#…

漏洞挖掘 | 某系统webpack接口泄露引发的一系列漏洞

信息搜集 这里找到从小穿一条裤子长大的兄弟&#xff0c;要挟他交出来他的统一账号&#xff0c;否则把小时候的照片挂网上&#xff0c;开始某大学的资产搜集&#xff0c;直接hunter搜索此大学域名 看有价值的站点&#xff0c;ok找到下面的站点 未授权敏感信息泄露越权任意用…

力扣高频SQL 50题(基础版)第四十二题之1517.查找拥有有效邮箱的用户

文章目录 力扣高频SQL 50题&#xff08;基础版&#xff09;第四十二题1517.查找拥有有效邮箱的用户题目说明实现过程准备数据实现方式结果截图总结 力扣高频SQL 50题&#xff08;基础版&#xff09;第四十二题 1517.查找拥有有效邮箱的用户 题目说明 表: Users -----------…

Dify on WeChat

Dify on WeChat 本项目为 chatgpt-on-wechat下游分支 额外对接了LLMOps平台 Dify&#xff0c;支持Dify智能助手模型&#xff0c;调用工具和知识库&#xff0c;支持Dify工作流。 Dify接入微信生态的详细教程请查看文章 手摸手教你把 Dify 接入微信生态 如果我的项目对您有帮助…

gin获得get和post请求参数,获得请求头信息

获得头信息 router.GET("/", func(c *gin.Context) {name : c.Query("id")fmt.Println(name)Token : c.GetHeader("Token")c.JSON(http.StatusOK, Token)})获得get和post信息 package mainimport ("fmt""github.com/SimonWang00…

Leetcode面试经典150题-236.二叉树的最低公共祖先

解法都在代码里&#xff0c;不懂就留言或者私信 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val x; }* }*/ class Solution {/**题目分析&#xff1a;本题是经典的二…

仓颉语言运行时轻量化实践

杨勇勇 华为语言虚拟机实验室架构师&#xff0c;目前负责仓颉语言静态后端的开发工作 仓颉语言运行时轻量化实践 仓颉Native后端&#xff08;CJNative&#xff09;是仓颉语言的高性能、轻量化实现。这里的“轻量化”意指仓颉程序运行过程中占用系统资源&#xff08;内存、CPU等…

数据分析:品牌营销如何借势小红书搜索流量

导语 近期&#xff0c;小红书推出《10大搜索趋势洞察》&#xff0c;在找答案这件事上&#xff0c;你永远可以相信小红书。 据悉&#xff0c;70%的小红狐月活用户使用搜索功能&#xff0c;用户平均每天搜索6次&#xff0c;三分之一的用户打开小红书的第一件事就是搜索&#xf…

haproxy知识点整理

haproxy知识点整理 haproxy七层代理负载均衡什么是负载均衡为什么使用负载均衡 负载均衡类型四层负载均衡七层负载均衡四层和七层的区别 环境搭建:客户端(client)haproxy服务器两台服务器hapserver1hapserver2 简单的haproxy负载均衡 haproxy的基本配置信息global配置proxies配…

2024高端网站设计公司推荐TOP3

随着互联网的飞速发展&#xff0c;现在的企业官网已经成为企业不可或缺的一部分&#xff0c;因为企业官网它不仅是企业品牌形象的延伸&#xff0c;也是连接客户、提升市场竞争力的重要工具。 以下简单阐述一下为何现代企业应当投资于高质量网站建设&#xff0c;搭建企业官网有…

html+css 实现图层水波纹效果

html+css 实现图层水波纹效果,废话不多说,直接上代码 <span class="quote-top"><i>水波纹</i><span class="ripple ripple-1"></span><span class="ripple ripple-2"></span><span class="…

打卡第四十一天:买卖股票的最佳时机

一、 买卖股票的最佳时机 题目 文章 视频 确定dp数组&#xff08;dp table&#xff09;以及下标的含义 dp[i][0] 表示第i天持有股票所得最多现金 。其实一开始现金是0&#xff0c;那么加入第i天买入股票现金就是 -prices[i]&#xff0c; 这是一个负数。dp[i][1] 表示第i天…

【MySQL】数据库约束和多表查询

目录 1.前言 2.数据库约束 2.1约束类型 2.2 NULL约束 2.3 NUIQUE&#xff1a;唯一约束 2.4 DEFAULT&#xff1a;默认值约束 2.5 PRIMARY KEY&#xff1a;主键约束 2.6 FOREIGN KEY&#xff1a;外键约束 1.7 CHECK约束 3.表的设计 3.1一对一 3.2一对多 3.3多对多 …