場景:html
在目標方法前面和後面執行通知方法java
目標類spring
@Component public class Play { public void watchTV(){ System.out.println("目標執行方法,正在看電視"); } }
切面類express
public class WatchTVAspect { public void beforeAdvice(){ System.out.println("切點函數執行前的方法"); } public void afterAdvice(){ System.out.println("切點函數執行後的方法"); } public void afterReturning(){ System.out.println("目標方法返回時執行 ,後置返回通知"); } public void afterThrowing(){ System.out.println("目標方法拋出異常時執行 異常通知"); } public void around(){ System.out.println("在目標函數執行中執行,可控制目標函數是否執行,環繞通知"); } }
applicationContext.xmlapp
<?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:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"> <context:component-scan base-package="com.mb"></context:component-scan> <bean id="watchTv" class="com.mb.util.WatchTVAspect"></bean> <aop:config> <aop:aspect id="check" ref="watchTv"> <aop:pointcut id="accountPoint" expression="execution(* com.mb.common.Play.*(..))"></aop:pointcut> <aop:before pointcut-ref="accountPoint" method="beforeAdvice"></aop:before> <aop:after pointcut-ref="accountPoint" method="afterAdvice"></aop:after> <!--<aop:around method="around" pointcut-ref="accountPoint" ></aop:around>--> <!--<aop:after-returning method="afterReturning" pointcut-ref="accountPoint"></aop:after-returning>--> <!--<aop:after-throwing method="afterThrowing" pointcut-ref="accountPoint"></aop:after-throwing>--> </aop:aspect> </aop:config> </beans>
測試類函數
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:**/applicationContext*.xml"}) public class DemoTest { @Autowired Play play; @Test public void aspectTest(){ play.watchTV(); } }
測試結果:切點函數執行前的方法目標執行方法,正在看電視切點函數執行後的方法