Spring 学习笔记----->AOP

Spring 学习笔记----->AOP

代理模式

为什么学代理模式?

因为这就是Spring Aop的底层

  • 代理模式的分类:
    • 静态代理
    • 动态代理
静态代理

生活用的例子:

image-20210509120104456

房东

public class Host implements Rent {
    @Override
    public void rent() {
        System.out.println("房东租房子");
    }
}

代理

public class Proxy {
    private Host host;
    public Proxy(){

    }

    public Proxy (Host host){
        this.host=host;
    }
    public void rent() {
        host.rent();
        seeHouse();
        hetong();
        fare();
    }

    public void seeHouse( ) {
        System.out.println("中介带你看房子");
    }
    public void hetong(){
        System.out.println("签订租赁合同");
    }
    public void fare(){
        System.out.println("收中介费");
    }
}

用户

public class Client {

    public static void main(String[] args) {
        //房东要租房子
        Host host = new Host();
        //代理  中介帮房东租房子   代理角色通常会添加一些附加操作
        Proxy proxy=new Proxy(host);
        //不用面对房东  直接找中介租房即可
        proxy.rent();
    }
}

image-20210509114631611

角色分析:

  • 抽象角色:一般使用抽象类或者接口解决
  • 真实角色: 被代理的角色
  • 代理角色:代理真实的角色 通常会加一些附加操作
  • 客户:访问代理对象的人

代理模式的好处:

  • 可以是真实角色的操作更加纯粹 不用去关注一些公共的业务
  • 公共业务交给代理角色 实现了业务的分工
  • 公共业务发生扩展 方便集中管理

缺点:一个真实角色就会产生一个代理角色 代码量翻倍 开发效率变低

理解

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l0V8XVBc-1620703702704)(https://phq-1304846428.cos.ap-nanjing.myqcloud.com/typora_pic/%E6%9C%AA%E5%91%BD%E5%90%8D%E6%96%87%E4%BB%B6%20(4)].jpg)

动态代理

动态代理和静态代理角色一样 ,不过它的代理类是动态生成的 不是我们直接写好的

动态代理分为两大类 基于接口的动态代理,基于类的动态代理

  • 基于接口:JDK动态代理 [此处学习这种]
  • 基于类 cglib
  • java字节码实现 :javasist

需要了解两个类:Proxy:代理 InvocationHandle调用处理程序

动态代理的好处:

  • 是真实角色操作更加纯粹 ,不用去关注一些公共的业务
  • 公共业务也交给代理角色,实现了业务的分工,
  • 公共业务发生扩展的时候 方便集中管理
  • 一个动态代理代理的是一个接口 一般对应的是一类业务
  • 一个动态代理类可以代理多个类 只要实现了同一个接口即可
AOP

AOP 领域中的特性术语:

  • 通知(Advice): AOP 框架中的增强处理。通知描述了切面何时执行以及如何执行增强处理。
  • 连接点(join point): 连接点表示应用执行过程中能够插入切面的一个点,这个点可以是方法的调用、异常的抛出。在 Spring AOP 中,连接点总是方法的调用。
  • 切点(PointCut): 可以插入增强处理的连接点。
  • 切面(Aspect): 切面是通知和切点的结合。
  • 引入(Introduction):引入允许我们向现有的类添加新的方法或者属性。
  • 织入(Weaving): 将增强处理添加到目标对象中,并创建一个被增强的对象,这个过程就是织入758949-20190529232014979-1838628294
使用spring实现Aop

不影响原来类的情况下实现动态增强

首先需要导入依赖包

  <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.9.3</version>
    </dependency>
public class AfterLog implements AfterReturningAdvice {
    @Override
    public void afterReturning(Object returnValue, Method method, Object[] objects, Object target) throws Throwable {
        System.out.println("执行了"+target.getClass().getName()+"的"+method.getName()
                +"方法,返回值为"+returnValue);
    }
}
public class BeforeLog implements MethodBeforeAdvice {
    //method 要执行对象的方法   objects参数 target 目标对象
    @Override
    public void before(Method method, Object[] objects, Object target) throws Throwable {
        System.out.println(target.getClass().getName()+"的"+method.getName()+"被执行了");
    }
}
方式1:原生Spring API
<?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
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

        <bean id="userService" class="com.phq.service.UserServiceImpl"/>
        <bean id="beforelog" class="com.phq.log.BeforeLog"/>
        <bean id="afterlog" class="com.phq.log.AfterLog"/>
<!--        方式1:原生Spring API接口-->
    <aop:config>
<!--       切入点-->
        <aop:pointcut id="point" expression="execution(* com.phq.service.UserServiceImpl.*(..))"/>
<!--        执行环绕增加-->
        <aop:advisor advice-ref="beforelog" pointcut-ref="point"/>
        <aop:advisor advice-ref="afterlog" pointcut-ref="point"/>
    </aop:config>
</beans>

测试:

    @Test
  public void Test1(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        //动态代理代理的是接口
        UserService userService = context.getBean("userService", UserService.class);
        userService.add();
    }

image-20210509213843171

方式2:自定义类实现AOP
//自定义类
public class DiyPointCut {
    public void before(){
        System.out.println("========方法执行前==========");
    }
    public void after(){
        System.out.println("========方法执行后==========");
    }
}
<!--    方式2:自定义类-->
    <bean id="diy" class="com.phq.diy.DiyPointCut"/>
    <aop:config>
<!--        自定义切面 ref要引用的类-->
        <aop:aspect ref="diy">
<!--            切入点-->
           <aop:pointcut id="point" expression="execution(* com.phq.service.UserServiceImpl.*(..))"/>
<!--            通知-->
            <aop:before method="before" pointcut-ref="point"/>
            <aop:after method="after" pointcut-ref="point"/>
        </aop:aspect>
    </aop:config>

image-20210509215255210

方法3:注解实现
@Aspect//标注这个类是一个切面
public class AnnotationPointCut {
    @Before("execution(* com.phq.service.UserServiceImpl.*(..))")
    public void before(){
        System.out.println("========方法执行前==========");
    }
    @After("execution(* com.phq.service.UserServiceImpl.*(..))")
    public void after(){
        System.out.println("========方法执行后==========");
    }
    //在环绕增强中 可以设定一个参数  代表我们获取数据切入的点
    @Around("execution(* com.phq.service.UserServiceImpl.*(..))")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前");
        //执行方法
        Object proced=pjp.proceed();
        //获得签名
        Signature signature = pjp.getSignature();
        System.out.println("signature:"+signature);
        System.out.println("环绕后");
    }
}
<!--    方式3:注解实现-->
    <bean id="AnnotationPointCut" class="com.phq.diy.AnnotationPointCut"/>
<!--    开启注解支持-->
    <aop:aspectj-autoproxy/>

image-20210509220735903

整合MyBatis
方式1:手动注入

导包:

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.26</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.6</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>5.2.14.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.2</version>
    </dependency>
  <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.12</version>
    </dependency>
</dependencies>

编写数据源:spring-dao.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 https://www.springframework.org/schema/context/spring-context.xsd">


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

<!--DateSource :使用Spring的数据源替换Mybatis的配置-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="${url}"/>
    <property name="username" value="root"/>
    <property name="password" value="${password}"/>
</bean>

<!--    SQLSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
<!--        绑定Mybatis配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <property name="mapperLocations" value="classpath:com/phq/dao/*.xml"/>
    </bean>
<!--    SQLSessionTemplate就是之前使用的SQLSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<!--        只能用构造器注入sqlSessionFactory  因为他没有set方法-->
        <constructor-arg index="0" ref="sqlSessionFactory"/>
    </bean>
   <bean id="userMapper" class="com.phq.dao.UserMapperImpl">
       <property name="sqlSessionTemplate" ref="sqlSession"/>
   </bean>
</beans>

使用jdbc.properties时可能出现数据库连接不上的情况,只需要将driverClassName和username属性直接写进去即可 具体原因未知,可能是因为读取properties配置文件导致连接超时。

测试:

    @Test
    public void testspring(){

        ApplicationContext context=new ClassPathXmlApplicationContext("spring-dao.xml");
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);

        for (User user : userMapper.getUserList()) {
            System.out.println(user);
        }
    }

image-20210511100241624

方式2:继承SqlSessionDaoSupport
public class UserMapperImpl2 extends SqlSessionDaoSupport implements UserMapper{
    @Override
    public List<User> getUserList() {
        return getSqlSession().getMapper(UserMapper.class).getUserList();
    }
}

设置bean

 <bean id="userMapper2" class="com.phq.dao.UserMapperImpl2">
        <property name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>
声明式事务

回顾事务

  • 把一组业务当成一个业务来做

  • 要么都成功 要么都失败

  • 涉及到数据的一致性问题

事务 ACID原则:

  • 原子性

  • 一致性

  • 隔离性

    • 多个业务可能操作同一个资源 防止数据损坏
  • 持久性

    • 事务一旦提交 无论系统发生什么问题,结果都不会受影响 持久化的写入到存储器中

      使用 MyBatis-Spring 的其中一个主要原因是它允许 MyBatis 参与到 Spring 的事务管理中。而不是给 MyBatis 创建一个新的专用事务管理器,MyBatis-Spring 借助了 Spring 中的 DataSourceTransactionManager 来实现事务管理。

    一旦配置好了 Spring 的事务管理器,你就可以在 Spring 中按你平时的方式来配置事务。并且支持 @Transactional 注解和 AOP 风格的配置。在事务处理期间,一个单独的 SqlSession 对象将会被创建和使用。当事务完成时,这个 session 会以合适的方式提交或回滚。事务配置好了以后,MyBatis-Spring 将会透明地管理事务。这样在你的 DAO 类中就不需要额外的代码了。

测试:将delete方法写错 执行后user插入成功

    public List<User> getUserList() {

        User user=new User(7,"测试事务","123456");
        UserMapper userMapper=getSqlSession().getMapper(UserMapper.class);
        userMapper.addUser(user);
        userMapper.deleteUser(7);
       return userMapper.getUserList();
    }

image-20210511111456440

配置事务

<!--    配置声明式事务-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <constructor-arg ref="dataSource"/>
</bean>
<!--    集合AOP实现事务的织入-->
<!--    配置事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
<!--      给哪些方法配置事务-->
<!--        配置事务的传播特性  new propagation-->
        <tx:attributes>
            <tx:method name="add" propagation="REQUIRED"/>
            <tx:method name="delete" propagation="REQUIRED"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
<!--    配置事务织入-->
<aop:config>
    <aop:pointcut id="txPointCut" expression="execution(* com.phq.dao.*.*(..))"/>
    <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"/>
</aop:config>

再次执行 不会插入user

为什么需要事务:

  • 如果不配置事务 可能存在数据不一致的情况
  • 如果不在spring中配置声明式事务 我们就需要在代码中手动配置事务
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

phqovo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值