Spring:AOP

9.AOP

9.1什么是AOP?

AOP(Aspect Oriented Programming)意为:面向切面编程,通过预编译方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,是函数式编程的一种衍生范型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-uu0jgmAy-1612345869804)(Spring.assets/image-20201128100411006.png)]

名词介绍:

  • 切面(ASPECT):横切关注点 被模块化 的特殊对象。即,它是一个类。
  • 通知(Advice):切面必须要完成的工作。即,它是类中的一个方法。
  • 目标(Target):被通知对象。
  • 代理(Proxy):向目标对象应用通知之后创建的对象。
  • 切入点(PointCut):切面通知 执行的 “地点”的定义。
  • 连接点(JointPoint):与切入点匹配的执行点。

Aop在Spring中的作用

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

在工作中,一些公共业务就可以通过Aop切入到业务中。

通知类型:

通知类型连接点实现接口
前置通知方法前org.springframework.aop.MethodBeforeAdvice
后置通知方法后org.springframework.aop.AfterReturningAdvice
环绕通知方法前和方法后org.aopalliance.intercept.MethodInterceptor
异常通知方法抛出异常org.springframework.ThrowsAdvice
引介通知类中增加新的方法属性org.springframework.aop.IntroductionInterceptor

9.2使用Spring实现AOP

导包aspectj

<!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
<dependency>
    <groupId>org.aspectj</groupId>
    <artifactId>aspectjweaver</artifactId>
    <version>1.9.6</version>
    <scope>runtime</scope>
</dependency>

9.2.1实现方式一

  1. 编写目标接口

    public interface UserService {
        void addUser();
        void deleteUser();
        void updateUser();
        void searchUser();
    }
    
  2. 编写目标类

    public class UserServiceImpl implements UserService {
        public void addUser() {
            System.out.println("添加用户");
        }
    
        public void deleteUser() {
            System.out.println("删除用户");
        }
    
        public void updateUser() {
            System.out.println("更新用户");
        }
    
        public void searchUser() {
            System.out.println("查询用户");
        }
    }
    
  3. 编写切面实现通知类型

    //前置通知类
    public class beforeAdvice implements MethodBeforeAdvice {
        public void before(Method method, Object[] objects, Object o) throws Throwable {
            System.out.println("前置通知");
        }
    }
    //后置通知类
    public class afterAdvice implements AfterReturningAdvice{
        public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
            System.out.println("后置通知");
        }
    }
    
  4. spring的xml配置,bean的注册以及aop配置

    <?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="aop1.UserServiceImpl"/>
    
        <!--  通知注册  -->
        <bean id="before" class="aop1.aspect.beforeAdvice"/>
        <bean id="after" class="aop1.aspect.afterAdvice"/>
    
        <!-- aop 配置  -->
        <aop:config>
            <!--   切入点     -->
            <aop:pointcut id="user" expression="execution(* aop1.UserServiceImpl.*(..))"/>
            <!--  通知      -->
            <aop:advisor advice-ref="before" pointcut-ref="user"/>
            <aop:advisor advice-ref="after" pointcut-ref="user"/>
        </aop:config>
    </beans>
    
  5. 编写测试类

    public class Controller {
        public static void main(String[] args) {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserService userService = context.getBean("userService", UserService.class);
            userService.addUser();
        }
    }
    

9.2.2实现方式二

  1. 编写接口

  2. 编写目标对象

  3. 编写切面

    public class MyAspect {
        public void before(){
            System.out.println("前置通知1");
        }
        public void after(){
            System.out.println("后置通知1");
        }
    }
    
  4. spring的xml配置,bean的注册以及aop配置(aop配置包括通知类型的配置)

    <?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="aop1.UserServiceImpl"/>
    
        <!--  通知注册  -->
        <bean id="before" class="aop1.aspect.beforeAdvice"/>
        <bean id="after" class="aop1.aspect.afterAdvice"/>
        <!--  切面注册  -->
        <bean id="aspect" class="aop2.aspect.MyAspect"/>
        <!-- aop 配置  -->
        <aop:config> 
            <!--   切入点     -->
            <aop:pointcut id="user" expression="execution(* aop1.UserServiceImpl.*(..))"/>
            <!--  通知      -->
    <!--        <aop:advisor advice-ref="before" pointcut-ref="user"/>-->
    <!--        <aop:advisor advice-ref="after" pointcut-ref="user"/>-->
    		<!--  切面设置      -->
            <aop:aspect id="myAspect" ref="aspect">
                <aop:before method="before" pointcut-ref="user"/>
                <aop:after-returning method="after" pointcut-ref="user"/>
            </aop:aspect>
        </aop:config>
    </beans>
    
  5. 编写测试类

    public class Controller {
        public static void main(String[] args) {
            ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserService userService = context.getBean("userService", UserService.class);
            userService.addUser();
        }
    }
    

9.9.3注解实现

  1. 编写接口

  2. 编写目标类

    @Component("userService1")
    public class UserServiceImpl implements UserService {
    
        public void addUser() {
            System.out.println("添加用户");
        }
    
        public void deleteUser() {
            System.out.println("删除用户");
        }
    
        public void updateUser() {
            System.out.println("更新用户");
        }
    
        public void searchUser() {
            System.out.println("查询用户");
        }
    }
    
  3. 编写切面

    @Aspect
    @Component
    public class MyAspect {
        @Before("execution(* aopAnnotation.UserServiceImpl.*(..))")
        public void before(){
            System.out.println("前置通知2");
        }
    
        @AfterReturning("execution(* aopAnnotation.UserServiceImpl.*(..))")
        public void after(){
            System.out.println("后置通知2");
        }
    }
    
  4. spring的xml配置,bean的注册以及aop配置

    <?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"
           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/aop
           http://www.springframework.org/schema/aop/spring-aop.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">
        <!--开启注解包扫描-->
        <context:component-scan base-package="aopAnnotation"/>
        <!-- 开启切面注解声明   -->
        <aop:aspectj-autoproxy/>
    </beans>
    
  5. 编写测试类

public class Controller {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring1.xml");
        UserService userService1 = context.getBean("userService1", UserService.class);
        userService1.deleteUser();
    }
}

通过aop命名空间的<aop:aspectj-autoproxy />声明自动为spring容器中那些配置@aspectJ切面的bean创建代理,织入切面。当然,spring 在内部依旧采用AnnotationAwareAspectJAutoProxyCreator进行自动代理的创建工作,但具体实现的细节已经被<aop:aspectj-autoproxy />隐藏起来了

<aop:aspectj-autoproxy />有一个proxy-target-class属性,默认为false,表示使用jdk动态代理织入增强,当配为<aop:aspectj-autoproxy poxy-target-class=“true”/>时,表示使用CGLib动态代理技术织入增强。不过即使proxy-target-class设置为false,如果目标类没有声明接口,则spring将自动使用CGLib动态代理。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值