JAVA全系列 教程
3762个小节阅读:7089k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
Spring可以使用注解代替配置文件配置切面:
在xml中开启AOP注解支持
xxxxxxxxxx
<!-- 开启注解配置Aop -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
在通知类上方加入注解@Aspect
在通知方法上方加入注解@Before/@AfterReturning/@AfterThrowing/@After/@Around
xxxxxxxxxx
@Aspect
@Component
public class MyAspectAdvice {
// 后置通知
@AfterReturning("execution(* com.itbaizhan.dao.UserDao.*(..))")
public void myAfterReturning(JoinPoint joinPoint) {
System.out.println("切点方法名:" + joinPoint.getSignature().getName());
System.out.println("目标对象:" + joinPoint.getTarget());
System.out.println("打印日志" + joinPoint.getSignature().getName() + "方法被执行了!");
}
// 前置通知
@Before("execution(* com.itbaizhan.dao.UserDao.*(..))")
public void myBefore() {
System.out.println("前置通知...");
}
// 异常通知
@AfterThrowing(value = "execution(* com.itbaizhan.dao.UserDao.*(..))",throwing = "ex")
public void myAfterThrowing(Exception ex) {
System.out.println("异常通知...");
System.err.println(ex.getMessage());
}
// 最终通知
@After("execution(* com.itbaizhan.dao.UserDao.*(..))")
public void myAfter() {
System.out.println("最终通知");
}
// 环绕通知
@Around("execution(* com.itbaizhan.dao.UserDao.*(..))")
public Object myAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("环绕前");
Object obj = proceedingJoinPoint.proceed(); // 执行方法
System.out.println("环绕后");
return obj;
}
}
测试:
xxxxxxxxxx
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext2.xml")
public class UserDaoTest2 {
@Autowired
private UserDao userDao;
@Test
public void testAdd(){
userDao.add(1);
}
}
如何为一个类下的所有方法统一配置切点:
在通知类中添加方法配置切点
xxxxxxxxxx
@Pointcut("execution(* com.itbaizhan.dao.UserDao.*(..))")
public void pointCut(){}
在通知方法上使用定义好的切点
xxxxxxxxxx
@Before("pointCut()")
public void myBefore(JoinPoint joinPoint) {
System.out.println("前置通知...");
}
@AfterReturning("pointCut()")
public void myAfterReturning(JoinPoint joinPoint) {
System.out.println("后置通知...");
}
配置类如何代替xml中AOP注解支持?
在配置类上方添加@EnableAspectJAutoProxy即可
xxxxxxxxxx
@Configuration
@ComponentScan("com.itbaizhan")
@EnableAspectJAutoProxy
public class SpringConfig {
}
1.在xml中开启AOP注解支持的标签为
A <aop:aspectj-auto>
B <aop:aspectj>
C <aop:aspectj-autoproxy>
D <aop:auto>
2.环绕通知的注解为
A @Before
B @After
C @Pointcut
D @Around
答案
1=>C 2=>D