AOP进阶样例-基于全注解

AOP进阶样例-基于全注解_第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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>aopartifactId>
    <version>1.0-SNAPSHOTversion>
    <packaging>jarpackaging>

    <dependencies>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-contextartifactId>
            <version>5.2.7.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.aspectjgroupId>
            <artifactId>aspectjweaverartifactId>
            <version>1.9.5version>
        dependency>
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-testartifactId>
            <version>5.2.7.RELEASEversion>
        dependency>
    dependencies>

    <repositories>
        <repository>
            <id>alimavenid>
            <name>aliyun mavenname>
            <url>http://maven.aliyun.com/nexus/content/groups/public/url>
            <releases>
                <enabled>trueenabled>
            releases>
            <snapshots>
                <enabled>falseenabled>
            snapshots>
        repository>
    repositories>

    <properties>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <java.version>14java.version>
        <maven.compiler.source>14maven.compiler.source>
        <maven.compiler.target>14maven.compiler.target>
        <encoding>UTF-8encoding>
    properties>


project>

代码:

package com.example.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@Configuration
@ComponentScan("com.example")
@EnableAspectJAutoProxy
public class Config {

}
package com.example.service;

/**
 * 账户的业务层接口
 */
public interface IAccountService {
    /**
     * 模拟保存账户
     */
    void saveAccount();

    /**
     * 模拟更新账户
     * @param i
     */
    void updateAccount(int i);

    /**
     * 模拟销毁账户
     * @return
     */
    int deleteAccount();
}
package com.example.service.impl;

import com.example.service.IAccountService;
import org.springframework.stereotype.Service;

/**
 * 账户的业务层实现类
 */
@Service("accountService")
public class AccountServiceImpl implements IAccountService {
    @Override
    public void saveAccount() {
        System.out.println("执行了保存");
    }

    @Override
    public void updateAccount(int i) {
        System.out.println("执行了更新:"+i);
    }

    @Override
    public int deleteAccount() {
        System.out.println("执行了删除");
        return 0;
    }
}
package com.example.utils;

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

/**
 * 用于记录日志的工具类,它里面提供了公共代码
 */
@Component("logger")
@Aspect
public class Logger {

    @Pointcut("execution(* com.example.service.impl.*.*(..))")
    private void pt1(){}
    /**
     * 前置通知 befor
     */
    @Before("pt1()")
    public void beforePrintLog(){
        System.out.println("Logger.beforePrintLog");
    }
    /**
     * 后置通知 after
     */
    @AfterReturning("pt1()")
    public void afterReturningPrintLog(){
        System.out.println("Logger.afterReturningPrintLog");
    }
    /**
     * 异常通知 throw
     */
    @AfterThrowing("pt1()")
    public void afterThrowingPrintLog(){
        System.out.println("Logger.afterThrowingPrintLog");
    }
    /**
     * 最终通知 finally
     */
    @After("pt1()")
    public void afterPrintLog(){
        System.out.println("Logger.afterPrintLog");
    }

    /**
     * 环绕通知:用于增强方法(pjp)
     * 问题:切入点方法未执行,通知方法在执行了
     * 解决:需要pjp.proceed方法显示调用切入点方法
     */
    @Around("pt1()")
    public Object aroundPrintLog(ProceedingJoinPoint pjp){
        System.out.println("Logger.aroundPrintLog");
        Object rtValue=null;
        Object[] args = pjp.getArgs();
        try {
            //前置
            rtValue=pjp.proceed(args);
            //后置
        } catch (Throwable throwable) {
            //异常
            throw new RuntimeException(throwable);
        }finally {
            //最终
        }
        return rtValue;
    }
}

测试:

package com.example.service;


import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = com.example.config.Config.class)
public class AccountServiceTest {

    @Autowired
    IAccountService service;

    @Test
    public void testSaveAccount(){
        service.saveAccount();
        service.updateAccount(0);
        service.deleteAccount();
    }
}

 

你可能感兴趣的:(AOP进阶样例-基于全注解)