Spring学习六、AOP与整合Mybatis

十一、AOP

AOP(Aspect Oriented Programming) 意为:面向切面编程

是通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。

AOP是OOP的一种延续,是软件开发的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。

利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各个部分之间的耦合度降低,提高程序的可重用性,同时提高开发效率。

AOP的作用及优势

  • 作用

    • 程序运行期间,不修改源码对已有方法进行增强
  • 优势
    • 减少重复代码
    • 提高开发效率
    • 维护方便

AOP在Spring中的作用

提供声明式事务:允许用户自定义切面

  • 横切关注点:跨越应用程序多个模板的方法或者功能。即是:与我们业务逻辑无关的,但是我们需要关注的部分,就是横切关注点。如日志,安全,缓存,事务等等......
  • 切面:横切关注点被模块化的一个对象。即:他是一个类
  • 通知:切面必须完成的工作。即:类中的方法
  • 目标:被通知的对象
  • 代理:向目标对象应用通知之后创建的对象。
  • 切入点:切面通知 执行的“地点”的定义。
  • 连接点:与切入点匹配的执行点。

使用String实现AOP

需要导入依赖包

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

方式一:使用Spring的接口

<?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:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 注册bean-->
    <bean id="userService" class="cn.imut.service.UserServiceImpl"/>

    <bean id="log" class="cn.imut.log.Log"/>
    <bean id="afterLog" class="cn.imut.log.AfterLog"/>
    <!-- 方式一、使用原生Spring API 接口-->
    <!-- 配置aop 需要导入aop的配置-->
    <aop:config>
        <!-- 切入点:expression:表达式   execution(要执行的位置)-->
        <aop:pointcut id="pointcut" expression="execution(* cn.imut.service.UserServiceImpl.*(..))"/>
        <!-- 执行环绕增强-->
        <aop:advisor advice-ref="log" pointcut-ref="pointcut"/>
        <aop:advisor advice-ref="afterLog" pointcut-ref="pointcut"/>
    </aop:config>

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //动态代理代理的是接口!
        UserService userService = (UserService) context.getBean("userService");

        userService.add();
    }
}

方式二:使用自定义类(主要是切面定义)

<!-- 方式二、自定义类-->
    <bean id="diy" class="cn.imut.diy.DiyPointCut"/>

    <aop:config>
        <!-- 自定义切面,ref 要引用的类-->
        <aop:aspect ref="diy">
            <!-- 切入点-->
            <aop:pointcut id="point" expression="execution(* cn.imut.service.UserServiceImpl.*(..))"/>
            <!-- 通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

测试

public class MyTest {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        //动态代理代理的是接口!
        UserService userService = (UserService) context.getBean("userService");

        userService.add();
    }
}

方式三:使用注解实现

    <!-- 方式三注册-->
    <bean id="annotationPointCut" class="cn.imut.diy.AnnotationPoint"/>

    <!-- 开启注解支持-->
    <aop:aspectj-autoproxy/>
@Aspect //标注这个类是一个切面
public class AnnotationPoint {

    @Before("execution(* cn.imut.service.UserServiceImpl.*(..))")
    public void before() {
        System.out.println("该方法执行前");
    }
}

eg2

//用户记录日志的公共类
@Component("logger")
@Aspect //当前类是一个切面类
public class Logger {
    //用于打印日志,计划让其在切入点方法执行之前执行

    @Pointcut("execution(* cn.imut.service.Impl.*.*(..))")
    public void pt1() {
        System.out.println("哈哈");
    }
    @Before("pt1()")
    public void printLog() {
        System.out.println("Logger类中的printLog方法开始记录日志了");
    }
}

十二、整合Mybatis

步骤:

  1. 导入jar包

    • junit
    • mybatis
    • mysql
    • spring相关
    • aop植入
    • mybatis-spring [new]
  2. 编写配置文件
  3. 测试

12.1 回忆Mybatis

  1. 编写实体类
  2. 编写核心配置文件
  3. 编写接口
  4. 编写Mapper.xml
  5. 测试

12.2 Mybatis-Spring

环境:

    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.2.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.8</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.4</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
        </dependency>
    </dependencies>
  1. 编写数据源配置

        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
            <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=true&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
            <property name="username" value="root"/>
            <property name="password" value="1870535196"/>
        </bean>
  2. sqlSessionFactory
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!-- 绑定Mybatis 配置文件
                可以替代Mybatis配置文件
            -->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
            <property name="mapperLocations" value="classpath:cn/imut/mapper/UserMapper.xml"/>
        </bean>
  3. sqlSessionTemplate
        <!-- SqlSessionTemplate:就是我们使用的sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
            <!-- 只能通过构造器注入,因为没有set方法-->
            <constructor-arg index="0" ref="sqlSessionFactory"/>
        </bean>
  4. 接口加实现类
    public interface UserMapper {
        public List<User> selectUser();
    }
    public class UserMapperImpl implements UserMapper{
    
        //我们的所有操作都使用SqlSession来执行
        private SqlSessionTemplate sqlSession;
    
        public void setSqlSession(SqlSessionTemplate sqlSession) {
            this.sqlSession = sqlSession;
        }
    
        public List<User> selectUser() {
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            return mapper.selectUser();
        }
    }
        <bean id="userMapper" class="cn.imut.mapper.UserMapperImpl">
            <property name="sqlSession" ref="sqlSession"/>
        </bean>
  5. 实现类注入Spring,测试
        @Test
        public void selectAll() {
            ApplicationContext context = new ClassPathXmlApplicationContext("spring-dao.xml");
            UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
            for (User user : userMapper.selectUser()) {
                System.out.println(user);
            }
        }

方式二

public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    public List<User> selectUser() {
        SqlSession session = getSqlSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        return mapper.selectUser();
    }
}
    <bean id="userMapper2" class="cn.imut.mapper.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

原文地址:https://www.cnblogs.com/yfyyy/p/12433425.html

时间: 2024-08-11 01:18:28

Spring学习六、AOP与整合Mybatis的相关文章

springmvc学习笔记(8)-springmvc整合mybatis之service

springmvc学习笔记(8)-springmvc整合mybatis之service springmvc学习笔记8-springmvc整合mybatis之service 定义service接口 在spring容器配置service 事务控制 本文记录如何整合service,包括定义spring接口,在spring容器配置service以及事务控制.让spring管理service接口. 定义service接口 public interface ItemsService { //商品查询列表 L

Spring学习(五)——集成MyBatis

本篇我们将在上一篇http://www.cnblogs.com/wenjingu/p/3829209.html的Demo程序的基础上将 MyBatis 代码无缝地整合到 Spring 中. 数据库仍然采用前一篇文章中定义的数据库sampledb. 1.修改gradle文件,增加依赖包,代码如下: apply plugin: 'idea' apply plugin: 'java' repositories { mavenCentral() maven { url "http://repo.spri

springmvc学习笔记(9)-springmvc整合mybatis之controller

springmvc学习笔记(9)-springmvc整合mybatis之controller springmvc学习笔记9-springmvc整合mybatis之controller springmvcxml 配置webxml 编写Controller就是Handler 编写jsp 本文介绍如何配置springmvc配置文件和web.xml,以及如何编写controller,jsp springmvc.xml 在resources/spring文件下下创建springmvc.xml文件,配置处理

spring boot 1.5.4 整合 mybatis(十二)

上一篇:spring boot 1.5.4 整合log4j2(十一) Spring Boot集成Mybatis 更多更详细的配置参考文件:application.properties和<SpringBoot之application配置详解>(新版本新增属性缺失)  或参考官网http://projects.spring.io/spring-boot/ Spring Boot集成Mybatis有两种方式: 方式一:传统的引入外部资源配置的方式,方便对mybatis的控制: 方式二:mybatis

spring学习 六 spring与mybatis整合

在mybatis学习中有两种配置文件 :全局配置文件,映射配置文件.mybatis和spring整合,其实就是把mybatis中的全局配置文件的配置内容都变成一个spring容器的一个bean,让spring容器进行托管.因此整合过程就是把mybatis全局配置文件的内容整合到spring的配置文件中 (一)mybatis全局配置文件 : 根标签是<configuration>, 子标签包括: <typeAliases>配置别名, <environments> 配置数据

spring学习(二) ———— AOP之AspectJ框架的使用

前面讲解了spring的特性之一,IOC(控制反转),因为有了IOC,所以我们都不需要自己new对象了,想要什么,spring就给什么.而今天要学习spring的第二个重点,AOP.一篇讲解不完,所以这篇文章主要介绍一下什么是AOP,如何去理解AOP.理解完之后,在spring中如何使用AspectJ AOP框架的.看得懂,写的出spring配置的那么就学的差不多了.加油.建议都自己手动实现一遍,这样才能更好的理解. --WH 一.什么是AOP? AOP:面向切面编程,采用横向抽取机制,取代了传

Spring学习-9-Spring与Hibernate整合

Spring与Hibernate整合 步骤 1)引入jar包 连接池/数据库驱动包 Hibernate相关jar包 Spring 核心包和aop包 Spring-orm Spring-tx 2)配置 hibernate.cfg.xml bean.xml 3)搭建 package com.cx.entity; /** * Created by cxspace on 16-8-11. */ public class Dept { private int id; private String name

Spring学习之Aop的基本概念

转自:http://my.oschina.net/itblog/blog/209067 AOP的基本概念 AOP从运行的角度考虑程序的流程,提取业务处理过程的切面.AOP面向的是程序运行中的各个步骤,希望以更好的方式来组合业务逻辑的各个步骤.AOP框架并不与特定的代码耦合,AOP框架能处理程序执行中特定切入点,而不与具体某个类耦合(即在不污染某个类的情况下,处理这个类相关的切点).下面是一些AOP的一些术语: 切面(Aspect):业务流程运行的某个特定步骤,也就是应用运行过程的关注点,关注点通

SpringBoot学习10:springboot整合mybatis

需求:通过使用 SpringBoot+SpringMVC+MyBatis 整合实现一个对数据库中的 t_user 表的 CRUD 的操作 1.创建maven项目,添加项目所需依赖 <!--springboot项目依赖的父项目--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId>