04-SpringAOP基于XML和注解配置
一、SpringAOP基于XML配置
1.1、XML文件格式
<?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"
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">
<!--切面类-->
<bean id="mom" class="com.oukele.learning.aop0.Mom"/>
<!--面向切面编程-->
<aop:config>
<!--定义切面-->
<aop:aspect ref="mom">
<!--定义切点-->
<aop:pointcut id="action" expression="execution(* *.*(..))"/>
<aop:before method="logStart" pointcut-ref="action"/>
<aop:after method="logEnd" pointcut-ref="action"/>
<aop:after-returning method="logReturn" pointcut-ref="action" returning="a"/>
<aop:after-throwing method="logException" pointcut-ref="action" throwing="e"/>
</aop:aspect>
</aop:config>
</beans>
1.2、切入点表达式
(1)、格式
execution([修饰符] 返回值类型 包名.类名.方法名(参数))
(2)、写法说明
全匹配方式:
public void com.service.impl.AccountServiceImpl.saveAccount(com.domain.Account)
访问修饰符可以省略
void com.service.impl.AccountServiceImpl.saveAccount(com.domain.Account)
返回值可以使用号,表示任意返回值
* com.service.impl.AccountServiceImpl.saveAccount(com.domain.Account)
包名可以使用*号,表示任意包,但是有几级包,需要写几个
* *.*.*.*.AccountServiceImpl.saveAccount(com.domain.Account)
使用..来表示当前包,及其子包
* com..AccountServiceImpl.saveAccount(com.domain.Account)
类名可以使用号,表示任意类
* com...saveAccount(com.domain.Account)
方法名可以使用号,表示任意方法
* com...( com.domain.Account)
参数列表可以使用,表示参数可以是任意数据类型,但是必须有参数
* com...()
参数列表可以使用..表示有无参数均可,有参数可以是任意类型
* com...(..)
全通配方式:
* ...(..)
二、SpringAOP基于注解配置
2.1、配置类
@Configuration
@ComponentScan(basePackages="com.XXX")
@EnableAspectJAutoProxy
public class SpringConfiguration {
}
2.2、切面类
@Component
@Aspect//表明当前类是一个切面类
public class LogAspects {
@Pointcut("execution(public int com.enjoy.cap10.aop.Calculator.*(..))")
public void pointCut(){};
//@before代表在目标方法执行前切入, 并指定在哪个方法前切入
@Before("execution(public int com.enjoy.cap10.aop.Calculator.*(..))")
public void logStart(){
System.out.println("除法运行....参数列表是:{}");
}
@After("pointCut()")
public void logEnd(){
System.out.println("除法结束......");
}
@AfterReturning("pointCut()")
public void logReturn(){
System.out.println("除法正常返回......运行结果是:{}");
}
@AfterThrowing("pointCut()")
public void logException(){
System.out.println("运行异常......异常信息是:{}");
}
@Around("pointCut()")
public Object Around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
System.out.println("@Arount:执行目标方法之前...");
Object obj = proceedingJoinPoint.proceed();//相当于开始调div地
System.out.println("@Arount:执行目标方法之后...");
return obj;
}
}
说明:文章少有原创,几乎大部分来自网络,只用于个人学习记录。如有原创作者看到文章,请海涵或联系我!
邮箱:1277005303@qq.com

浙公网安备 33010602011771号