SSM-Spring-13:Spring中RegexpMethodPointcutAdvisor正则方法切入点顾问

时间:2023-01-05 14:49:39
------------吾亦无他,唯手熟尔,谦卑若愚,好学若饥-------------

RegexpMethodPointcutAdvisor:正则方法切入点顾问

  核心:

  <property name="pattern" value=".*do.*"></property> 表示方法全名(包名,接口名,方法名)
  运算符    名称     意义
  .        点号      表示任意单个字符
  +       加号      表示前一个字符出现一次或者多次
  *       星号      表示前一个字符出现0次或者多次

  具体使用案例:

  一个实现俩个方法的类:SomeServiceImpl

package cn.dawn.day16advisor02;

/**
* Created by Dawn on 2018/3/8.
*/
public class SomeServiceImpl {
public void doSome() {
System.out.println("do something");
}
public void doAny() {
System.out.println("do Any");
}
}

  一个实现任意增强的接口的方法:此处是实现后置增强的,我起名LoggerAfter

package cn.dawn.day16advisor02;

import org.springframework.aop.AfterReturningAdvice;

import java.lang.reflect.Method;

/**
* Created by Dawn on 2018/3/5.
*/
/*后置增强*/
public class LoggerAfter implements AfterReturningAdvice {
public void afterReturning(Object o, Method method, Object[] objects, Object o1) throws Throwable {
System.out.println("===============after==================");
}
}

  大配置文件:

<?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"
xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
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 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--要增强的对象-->
<bean id="service" class="cn.dawn.day16advisor02.SomeServiceImpl"></bean>
<!--增强的内容-->
<bean id="myadvice" class="cn.dawn.day16advisor02.LoggerAfter"></bean>
<!--顾问-->
<bean id="myadvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="myadvice"></property>
<property name="pattern" value=".*do.*"></property>
<!--上面那个name还有一个可以是patterns,value可以写多个正则。用逗号分割,匹配多个正则,方法名只要合适其中一个正则就增强-->
</bean>
<!--代理工厂bean-->
<bean id="proxyfactory" class="org.springframework.aop.framework.ProxyFactoryBean">
<!--要增强的对象-->
<property name="target" ref="service"></property>
<!--增强的内容-->
<property name="interceptorNames" value="myadvisor"></property>
</bean> </beans>

  单测方法:

package cn.dawn.day16advisor02;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; /**
* Created by Dawn on 2018/3/3.
*/
public class test20180310 {
@Test
/*aop代理工厂bean异常增强*/
public void t01(){
ApplicationContext context=new ClassPathXmlApplicationContext("ApplicationContext-day16advisor02.xml");
SomeServiceImpl service = (SomeServiceImpl) context.getBean("proxyfactory"); service.doSome();
service.doAny(); }
}