一、配置文件
<?xml version="1.0" encoding="utf-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
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 https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd"
xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p">
<!-- 第二种:PointcutAdvisor 切点切面-->
<!--例一:JdkRegexpMethodPointcut或NameMatchMethodPointcu定义切点,DefaultPointcutAdvisor 最常用的切面类型,它可以通过任意Pointcut和Advice 组合定义切面-->
<!--1、被代理目标对象-->
<bean id="heloTarget" class="test.spring.proxyServices.Impl.GreetServiceImpl"/>
<!--2、定义通知-->
<bean id="heloAdvice" class="test.spring.proxy.GreetServiceBeforeAdvice"/>
<!--3、定义切点-->
<!--法一、正则表达式匹配法拦截-->
<bean id="regCut" class="org.springframework.aop.support.JdkRegexpMethodPointcut">
<property name="pattern" value=".*gre.*"/>
</bean>
<!--法二、方法名匹配法拦截-->
<!--<bean id="nameCut" class="org.springframework.aop.support.NameMatchMethodPointcut">-->
<!--<property name="mappedName" value="greet"/>-->
<!--</bean>-->
<!--4、DefaultPointcutAdvisor将pointcut和advice关联 切面 = 切点+通知-->
<bean id="defaultAdvisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
<property name="pointcut" ref="regCut"/>
<property name="advice" ref="heloAdvice"/>
</bean>
<!--5、定义代理Bean-->
<bean id="heloService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>defaultAdvisor</value>
</list>
</property>
<property name="target" ref="heloTarget"/>
</bean>
<!--例二: RegexpMethodPointcutAdvisor 构造正则表达式切点切面-->
<!--被代理目标对象-->
<bean id="hiTarget" class="test.spring.proxyServices.Impl.GreetServiceImpl"/>
<!--定义通知-->
<bean id="hiAdvice" class="test.spring.proxy.GreetServiceBeforeAdvice"/>
<!--定义切面=切点+通知-->
<bean id="regexAdvisor" class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice" ref="hiAdvice"/>
<property name="patterns" value=".*gree.*"/>
</bean>
<bean id="hiService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="interceptorNames">
<list>
<value>regexAdvisor</value>
</list>
</property>
<property name="target" ref="hiTarget"/>
</bean>
</beans>
二、测试
public class SpringAopAction {
@Test
public void test(){
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
GreetService greetService1 = (GreetService)applicationContext.getBean("heloService");
greetService.greet("wwwyyyjjj");
GreetService greetService2 = (GreetService)applicationContext.getBean("hiService");
greetService.greet("wyjwyj");
}
}