AspectJ使用

给下面这个方法增强功能

import org.springframework.stereotype.Component;
/**
 * @Classname: AopTest
 * @Description:
 * @Author: Stonffe
 * @Date: 2023/3/30 20:19
 */
@Component
public class AopTest {
    public void func() {
        System.out.println("function...");
    }
}

切面

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

/**
 * @Classname: AopProxy
 * @Description:
 * @Author: Stonffe
 * @Date: 2023/3/30 20:29
 */
@Aspect
@Component
public class AopAspect {
    @Before("execution(public * com.sora.aop.AopTest.func(..))")
    public void before() {
        System.out.println("before...");
    }
    @AfterReturning("execution(public * com.sora.aop.AopTest.func(..))")
    public void afterReturning() {
        System.out.println("afterReturning..");
    }
    @After("execution(public * com.sora.aop.AopTest.func(..))")
    public void after() {
        System.out.println("after..");
    }
    @Around("execution(public * com.sora.aop.AopTest.func(..))")
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("before around..");
        Object retVal = pjp.proceed();
        System.out.println("after around..");
        return retVal;
    }
}

配置Aspectj

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

/**
 * @Classname: AopConfig
 * @Description:
 * @Author: Stonffe
 * @Date: 2023/3/30 20:21
 */
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages = {"com.sora.aop"})
public class AopConfig {
}

结果

public class Aoptest {
    @Test
    public void testAop() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        AopTest bean = context.getBean(AopTest.class);
        bean.func();
    }
}
before around..
before...
function...
after around..
after..
afterReturning..
posted @ 2023-03-30 21:04  xiaoovo  阅读(20)  评论(0)    收藏  举报