Spring06——基于注解的AOP

基于注解的SpringAop需要注意以下几点:

1.在配置文件中加入aop的命名空间

<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"
       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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

2.在配置文件中加入如下配置:

3.把横切关注点的代码抽象到切面类中

1)将切面类注入到IOC容器中 ,可以使用@Comment

2)给切面类添加@Aspect注解

4.在切面类种声明各种通知(方法):

1)通知包括前置通知:@Before  

              后置通知:@After 

            环绕通知:  @Around

扫描二维码关注公众号,回复: 4789053 查看本文章

2)这里要注意AspectJ切入点表达式

3)可以在通知方法中加入JoinPoint参数,他可以获得链接细节,比如方法名和参数

下面写个例子:

1.项目结构

2.pom:

<?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.spring03</groupId>
    <artifactId>spring03</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.0.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.0.8.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.0.8.RELEASE</version>
        </dependency>

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


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

        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

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




    </dependencies>
</project>

3.配置文件.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"
       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/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--配置自动扫描的包-->
    <context:component-scan base-package="com.spring.AnnoationAop"></context:component-scan>

    <!--使Aspectj注解起作用:自动为匹配的类生成代理对象-->
    <aop:aspectj-autoproxy> </aop:aspectj-autoproxy>

</beans>

4.接口+实现+切面+main:

1)接口:

package com.spring.AnnoationAop;

/**
 * @Author: wj
 * @Date: 2018/12/2 16:15
 * @Version 1.0
 */
public interface ArithmeticCalulator {
    int add(int i, int j);

    int sub(int i, int j);

    int mul(int i, int j);

    int div(int i, int j);

}

2)实现:

package com.spring.AnnoationAop;

import org.springframework.stereotype.Service;

/**
 * @Author: wj
 * @Date: 2018/12/2 16:16
 * @Version 1.0
 */
@Service 
public class ArithmeticCalulatorImpl implements ArithmeticCalulator {
    public int add(int i, int j) {

        int result = i+j ;

        return result;
    }

    public int sub(int i, int j) {
        int result = i-j ;
        return result;
    }

    public int mul(int i, int j) {
        int result = i*j ;
        return result;
    }

    public int div(int i, int j) {
        int result = i/j ;
        return result;
    }
}

3)切面:

package com.spring.AnnoationAop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @Author: wj
 * @Date: 2018/12/3 11:14
 * @Version 1.0
 */

//1.把该类放入IOC容器中、
//2.声明为一个切面

@Aspect
@Component
public class LoggingAspect {
    //声明该方法是前置通知
    @Before("execution(public int com.spring.AnnoationAop.ArithmeticCalulatorImpl.*(int ,int ))")
    public void beaforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The Method:"+methodName+" begins:"+args);
    }
}

4)main:

package com.spring.AnnoationAop;

import com.spring.aop.ArithmeticCalulatorLogProxy;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @Author: wj
 * @Date: 2018/12/3 10:09
 * @Version 1.0
 */
public class Main {
    public static void main(String[] args) {

        //1.创建spring 的ioc容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

        //2.从ioc容器中获取bean的实例

        ArithmeticCalulator arithmeticCalulator = ctx.getBean(ArithmeticCalulator.class);

        //3.使用bean

        int result = arithmeticCalulator.add(1,2);

        System.out.println("-->"+result);
    }
}

输出:

补充一下aop的5种通知:

package com.spring.AnnoationAop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

import static com.sun.xml.internal.ws.dump.LoggingDumpTube.Position.Before;

/**
 * @Author: wj
 * @Date: 2018/12/3 11:14
 * @Version 1.0
 */

//1.把该类放入IOC容器中、
//2.声明为一个切面

@Aspect
@Component
public class LoggingAspect {
    //声明该方法是前置通知
    @Before("execution(public int com.spring.AnnoationAop.ArithmeticCalulatorImpl.*(int ,int ))")
    public void beaforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The Method:"+methodName+" begins:"+args);
    }


    //后置通知(无论是否发生异常)
    @After(("execution(* com.spring.AnnoationAop.ArithmeticCalulatorImpl.*(..))"))
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("The Method:"+methodName+" after:"+args);
    }


    //返回通知(在方法正常结束后执行的)
    //返回通知是可以访问到方法的返回值的
    @AfterReturning(value = "execution(* com.spring.AnnoationAop.ArithmeticCalulatorImpl.*(..))",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("end width:"+result);
    }

    //异常通知
    //可以访问到y异常对象;且可以指定在出现特定异常时在执行通知
    @AfterThrowing(value = "execution(* com.spring.AnnoationAop.ArithmeticCalulatorImpl.*(..))",throwing = "ex")
    public void  afterThrowing(JoinPoint joinPoint,Exception ex){
        String methodName = joinPoint.getSignature().getName();
        List<Object> args = Arrays.asList(joinPoint.getArgs());
        System.out.println("Exception:"+ex);
    }


    //环绕通知
    //环绕通知需要ProcedingJoinPoint类型的参数
    //环绕通知类似动态代理的全过程:ProceedingJoinPoint 类型的参数可以决定是否执行目标方法,且环绕通知必须有返回值,返回值即为目标方法的返回值
    @Around(value = "execution(* com.spring.AnnoationAop.ArithmeticCalulatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint){
        Object result = null;
        //执行目标方法
        try {
            //前置通知
            System.out.println("前置通知");
            result = proceedingJoinPoint.proceed();
            //返回通知
            System.out.println("返回通知:"+result);
        } catch (Throwable throwable) {
            //异常通知
            throwable.printStackTrace();
        }
        //后置通知
        System.out.println("后置通知");
        return 100;

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38520617/article/details/84761194
今日推荐