spring 的 切片Aspect

时间:2023-03-09 18:07:04
spring 的 切片Aspect

语法: 

    <aop:config>
<!-- 配置多个切点,&& || ! -->
<aop:pointcut id="pc" expression="execution(public * com.wtas.*.service.*.*(..)) || execution(public * com.wtas.*.*.service.*.*(..)) || execution(public * com.wtas.*.*.*.service.*.*(..))" />
<aop:advisor pointcut-ref="pc" advice-ref="userTxAdvice" />
</aop:config>

其中,&&,||,可以写成and,or,但是需要注意大小写,我在讲||换成大写的OR的时候,不能进行事务控制,不知道是不是区别别大小写的。

1.controller方法:

spring 的 切片Aspect

 @Aspect
@Component
public class TimeAspect { @Around("execution(* com.sea.web.controller.UserController.*(..))")
public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("time aspect start");
//说明:ProceedingJoinPoint 可获取调用的方法的传入参数的值
//如:http:localhost:8080/user/1
//comtroller 方法:public User getInfo(@PathVarable String id)
Object[] args = pjp.getArgs();
for (Object arg : args) {
System.out.println("arg is " + arg); //id 1
}
long start = new Date().getTime();
// 此object 就是条用 方法的返回值 如:User user= UserController.findUser(),
//该方法相当于过滤器中dofilter()方法
Object object = pjp.proceed(); System.out.println("time aspect 耗时:" + (new Date().getTime() - start));
System.out.println("time aspect end");
return object;
} }

//@Around  : 包含以下三种

 Before Advice

代用之前的处理

After Advice

调用之后的处理

Throw Advice

调用的时候抛出的异常处理

execution(* com.sea.web.controller.UserController.*(..))
execution :表示执行
第一个 * :返回值 ;这代表 无论为什么返回值都行
com.sea.web.controller.UserController: 表示那个类
第二个 * :表示方法:类下的所有方法
*(..) :所有方法,任何参数的方法都执行
 

Anotation注解规则:

@Aspect表示注解的类是抽象的服务方法模块;

@Pointcut定义服务的使用规则,也就是服务方法要应用到目标类中哪些方法上。

@Pointcut("execution(*add*(..))") 第一个*表示不论是否有返回值,所有以add开头的方法,不管是否有参数。

private voidaddAddMethod(){};该方法只是注解模式中一个空的方法体,是一个模式化的方法定义结构,该方法不能有返回值,不能有任何参数,也不能对其进行实现。在Advice中要使用该方法名的标识。

Advice注解checkSecurity()方法,表示该方法是具体的服务方法,使用注解的方式,Advice不出现,而是使用上面理论部分提到的使用@After、@Befor、@Throw来表示,同时要在Advice中关联pointcut中定义的规则。

/*
* 拦截器
*/
@Component
@Aspect //切面
public class NamecheckIntercepter {
@Before("execution(public com.icil.entity.Customer com.icil.service.CustomerServiceImpl.*(..))")
public void beforeInteface(){
System.out.println("findCustomerById "+"切面 调用前*******************"); }
@After("execution(public com.icil.entity.Customer com.icil.service.CustomerServiceImpl.*(..))")
public void afterInteface(){
System.out.println("findCustomerById "+"切面 调用后"); } }