美文网首页
九.Spring AOP

九.Spring AOP

作者: A_x_A | 来源:发表于2019-03-10 23:27 被阅读0次

AOP 面向切面编程 (基本上是通过代理机制实现的)
通过提供另一种思考程序的方式来补充OOP(面向对象编程)
AOP是横向抽取,OOP是纵向抽象。

AOP核心概念

  • Aspect(切面):将关注点进行模块化。可以使用常规类或使用@Aspect注解来实现切面。
  • Join Point(连接点):一个连接点总是代表一个方法的执行。在程序执行过程中某个特定的点,如某方法调用时或异常处理时。
  • Advice(通知/增强):在特定的切入点上执行的增强处理,有before,after,afterReturning,afterThrowing,around
  • Pointcut(切点):匹配连接点的断言
  • Introduction(引入):声明额外的方法或某个类型的字符段
  • Target Object(目标对象):被一个或多个切面所通知的对象
  • AOP Proxy(AOP代理):AOP框架创建的对象,代理就是目标对象的加强。Spring中的AOP代理可以使JDK动态代理,也可以是CGLIB代理,前者基于接口,后者基于子类
  • Weaving(织入):
    其中,Advice的主要类型有:
  • Before Advice(前置通知)
  • After Returning Advice(返回后通知)
  • After Throwing Advice(抛出异常后通知)
  • After (finally)Advice(最后通知)
  • Around Advice(环绕通知)

例子

  • 1.添加依赖
<?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>com.spring</groupId>
  <artifactId>AOP</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>AOP</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <spring.version>5.1.5.RELEASE</spring.version>
    <aspectj.version>1.9.2</aspectj.version>
    <junit.version>4.12</junit.version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.7.12</slf4j.version>
  </properties>

  <dependencies>

    <!--spring-context依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--spring-aop依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--aspectj依赖-->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>${aspectj.version}</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>${aspectj.version}</version>
    </dependency>

    <!--spring-test依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--junit依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- log4j日志依赖 -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

  • 2.创建接口(Hello)和实现类(HelloImpl)
package com.spring;
public interface Hello {
    String hello();
}

package com.spring;

public class HelloImpl implements Hello {

    @Override
    public String hello() {
        return "Hello Spring AOP";
    }
}

  • 3.前置增强类(MyBeforeAdvice)
package com.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
* 用户自定义前置增强类
* */
public class MyBeforeAdvice {
   /* private static final Logger logger = LoggerFactory.getLogger(MyBeforeAdvice.class);*/
    public void beforeMethod(){
       /* logger.debug("This is a before method...");*/
        System.out.println("This is a before method");
    }
}

  • 4.配置文件(bean.xml)
<bean id="hello" class="com.spring.HelloImpl"/>
<bean id="myBeforeAdvice" class="com.spring.MyBeforeAdvice"/>

<aop:config>
    <aop:aspect id="before" ref="myBeforeAdvice">
        <aop:pointcut id="myPoinCut" expression="execution(* com.spring.*.*(..))"/>
        <aop:before method="beforeMethod" pointcut-ref="myPoinCut"/>
    </aop:aspect>
</aop:config>
  • 5.应用主类(HelloAPP)
package com.spring;

        import org.springframework.context.ApplicationContext;
        import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloAPP {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Hello hello = context.getBean(Hello.class);
        System.out.println(hello.hello());
    }

}

  • 6.运行结果
AOP运行截图.png

可以看到:Mybefore的方法被织入到了Hello的调用方法前面,前置增强生效

实战练习

“武松打虎”——武松(Fighter)在山里等着老虎(Tiger)在山里等着老虎(Tiger)出现,只要发现老虎出来,就打老虎。

  • 定义业务类型(Tiger类)

package com.spring;

public class Tiger {
    public void walk() {
        System.out.println("Tiger is walking...");
    }

}

  • 定义切面和配置---前置通知和后置通知(Fighter类)

package com.spring;

import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class Fighter {
    @Pointcut("execution(* com.spring.Tiger.walk())")
    public void foundTiger() {//里面不可加代码!!!!

    }

    @Before(value = "foundTiger()")
    public void foundBefore() {
        System.out.println("Fighter wait for tiger...");
    }

    @AfterReturning("foundTiger()")
    public void foundAfter() {
        System.out.println("Fighter fight with tiger...");
    }

}

  • 配置文件(bean.xml)
 <!--启动aspectj支持-->
    <aop:aspectj-autoproxy/>
    <!--配置bean-->
    <bean id="tiger" class="com.spring.Tiger"/>
    <bean id="fighte" class="com.spring.Fighter"/>
  • 主程序(FighterApp)
package com.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class FighterApp {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Tiger tiger = context.getBean(Tiger.class);
        tiger.walk();
    }
}

  • 运行截图


    运行结果.png

相关文章

网友评论

      本文标题:九.Spring AOP

      本文链接:https://www.haomeiwen.com/subject/vysmpqtx.html