前面几节我们使用三种方式完成了代理,接下来,我们将看一下在spring中如何完成aop。
<?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.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 用于扫描约定路径下所有的类,把包含@Component的类进行实例化 -->
<context:component-scan base-package="net.wanho.aspect"></context:component-scan>
<!-- 在上述扫描的基础上,如果有一个@Aspect的类,则会产生代理类 -->
<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
</beans>
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import java.util.Arrays;
@Aspect
@Component
public class MyAspect {
@Pointcut("execution(* net.wanho.aspect.StudentService.*())")
public void pointCut(){}
@After("pointCut()")
public void testPointcut()
{
System.out.println("testPointcut");
}
@Before("execution(* net.wanho.aspect.StudentService.*(..))")
public void security(JoinPoint joinPoint)
{
System.out.println(joinPoint.getKind()+"."+joinPoint.getSignature().getName()+":("+Arrays.toString(joinPoint.getArgs())+")");
System.out.println("权限");
}
@Around("execution(* net.wanho.aspect.StudentService.*(int)))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("around in");
Object object = proceedingJoinPoint.proceed();
System.out.println("around out");
return object;
}
@AfterThrowing("execution(* net.wanho.aspect.StudentService.*(int)))")
public void afterThrowing()
{
System.out.println("exception");
}
@AfterReturning("execution(* net.wanho.aspect.StudentService.*(int)))")
public void afterReturning()
{
System.out.println("return");
}
}
public interface StudentService {
void query();
}
import net.wanho.class134.entity.Student;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component(value = "studentService")
public class StudentServiceImpl implements StudentService {
@Override
public void query() {
System.out.println("查询");
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
public static void main(String[] args) throws Exception {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-aop-anno.xml");
StudentService studentService = applicationContext.getBean("studentService", StudentService.class);
studentService.query();
}
}
以上就是采用注解方式完成aop的过程。
原文:https://www.cnblogs.com/alichengxuyuan/p/12554684.html