SpringAop使用注意事项

SpringAop使用注意事项

“d485d551-fd68-4c3a-8e3b-90a83838b58c”

顺序

@Around  ==》 @Before  ==》 @Around ==》 @After ==》  @AfterReturning
@AfterThrowing : 执行目标方法时发生了异常,导致目标方法结束执行。然后@AfterReturning不会执行(目标方法是抛出异常)。目标方法自己有
try-catch没有抛出异常,@AfterReturning会正常执行,只不过拿到的返回值为null。

AspectComponent .java

package org.example;

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

/**
 * aop组件
 */
@Aspect
@Component
public class AspectComponent {

    @Pointcut("execution(* org.example.*.*(..))")
    public void pointCut(){

    }


    // 在目标方法 没有执行的时候开始执行 一般用于改变某个方法的入参值
    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        User arg = (User) args[0];
        System.out.println(arg.getName()+"xingming");
        arg.setName("doulongfe");
        System.out.println(args);
        System.out.println("before------------"+joinPoint.toString());
    }

    // 在目标方法执行return前执行 一般可以用于在return前执行插入的业务逻辑
    @After("pointCut()")
    public void after(JoinPoint joinPoint) {
        Object target = joinPoint.getTarget();
        System.out.println(target);
        System.out.println("after-----------"+joinPoint.toString());
    }


    // 如果同时使用了@Around 这个切面方法的话,这里的返回值是@Around方法的返回值。并不是原来方法的返回值。【出现异常,不执行】
    // 一般用于 修改返回值,或者拿到返回值后再执行自己一段业务逻辑
    @AfterReturning(pointcut = "pointCut()", returning = "returnVal")
    public void afterReturning(JoinPoint joinPoint, Object returnVal) {
        User user = (User) returnVal;
        System.out.println(user+"更新后返回值");
        System.out.println("afterReturning--------------"
                + returnVal +joinPoint.toString());
    }

    // 一顶要把pjp.proceed();的值return出去,否则会是@AfterReturning 拿不到返回值。
    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("around start-------===========--------");
        try {
            Object proceed = pjp.proceed();
            System.out.println(proceed+"返回值");
            return proceed;
        } catch (Throwable ex) {
            System.out.println("error in around");
//            throw ex;
        }
        System.out.println("around end---------===============-----------");
        return null;
    }

    @AfterThrowing(pointcut = "pointCut()", throwing = "error")
    public void afterThrowing(JoinPoint joinPoint, Throwable error) {
        System.out.println("error:" + error+joinPoint.toString());
    }

    // @Around  ==》 @Before  ==》 @Around ==》 @After ==》  @AfterReturning
    //  @AfterThrowing : 执行目标方法时发生了异常,导致目标方法结束执行。然后@AfterReturning不会执行(目标方法是抛出异常)。目标方法自己有
    //  try-catch没有抛出异常,@AfterReturning会正常执行,只不过拿到的返回值为null。

}



main.java

package org.example;


import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world!");
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
        System.out.println(ctx.getBean("userService"));

        // 测试用户服务aop过程
        UserService userService=ctx.getBean(UserService.class);
        User user = new User("jack","123456");
//        userService.addUser(user);
//        System.out.println("======================================================================");
//        userService.deleteUser(user);
        System.out.println("======================================================================");
        userService.updateUser(user);
        ctx.close();

    }
}

UserService.java

package org.example;

import org.springframework.stereotype.Service;

/**
 * 用户服务类
 */
@Service
public class UserService {
    /**
     * 增加用户
     */
    public void addUser(User user) {
        System.out.println("增加用户:"+user.toString());
    }
    /**
     * 删除用户
     */
    public void deleteUser(User user){
        System.out.println("删除用户:"+user.toString());
//        throw new RuntimeException("edit person throw exception");
    }

    public User updateUser(User user){
        System.out.println("更新用户:"+user.toString());
        user.setName("更新了姓名");
        try {
//            int a=1/0;
        } catch (Exception e) {

            System.out.println("发生了错误:"+e.getMessage());
        }
        return user;
//        throw new RuntimeException("edit person throw exception");
    }

}


User.java

package org.example;

/**
 * 用户类
 */
public class User {
    private String name;
    private String password;

    public User() {
    }

    public User(String name, String password) {
        this.name = name;
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "demo.aop.User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}



application.xml 在resource目录下

<?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
                           http://www.springframework.org/schema/context/spring-context.xsd">
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="org.example" />
</beans>

pom.xml

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

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.9</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.7</version>
        </dependency>
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-archetype-plugin</artifactId>
            <version>3.2.0</version>
        </plugin>
    </plugins>

    </build>
</project>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值