SpringAOP增強是什么,不知道的到上一章去找,這里直接上注解實現的代碼(不是純注解,純注解后續會有)
創建業務類代碼
1 @Service("dosome")//與配置文件中<bean id="dosome" class="com.com.service.DoSome"/>一樣 2 public class DoSome { 3 public void dosome(){ 4 System.out.println("我是service層"); 5 } 6 //該方法為了對比最終增強和后置增強的效果,還有就是異常拋出增強的效果 7 public void error(){ 8 int result=5/0;//偽造一個異常 9 System.out.println("我是異常方法"); 10 } 11 }
創建通知類代碼
1 @Aspect//標注這個類是一個切面 2 @Component//作用與@Service作用相同 3 public class Advice implements AfterAdvice { 4 //標注一個切點,這個方法只是為了寫一個表達式,什么都不用做 5 @Pointcut("execution(* com.cn.service.*.*(..))") 6 public void pointcut(){} 7 //前置增強 8 @Before("pointcut()") 9 public void before(JoinPoint jp){ 10 System.out.println("我是方法"+jp.getSignature().getName()+"的前置增強!"); 11 } 12 //后置增強 13 @AfterReturning(value = "pointcut()",returning = "obj") 14 public void afterReturning(JoinPoint jp,Object obj){ 15 System.out.println("我是方法"+jp.getSignature().getName()+"的后置增強!"+",返回值為"+obj); 16 } 17 //環繞增強 18 @Around("pointcut()") 19 public void around(ProceedingJoinPoint jp) throws Throwable { 20 System.out.println("我是環繞增強中的前置增強!"); 21 Object proceed = jp.proceed();//植入目標方法 22 System.out.println("我是環繞增強中的后置增強!"); 23 } 24 //異常拋出增強 25 @AfterThrowing(value = "pointcut()",throwing = "e") 26 public void error(JoinPoint jp,Exception e){ 27 System.out.println("我是異常拋出增強"+",異常為:"+e.getMessage()); 28 } 29 //最終增強 30 @After("pointcut()") 31 public void after(JoinPoint jp){ 32 System.out.println("我是最終增強"); 33 } 34 }
核心配置文件applicationContext.xml
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:context="http://www.springframework.org/schema/context" 5 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"> 6 <!--包掃描--> 7 <context:component-scan base-package="com.cn"/> 8 <!--開啟ioc注解--> 9 <context:annotation-config/> 10 <!--開啟aop注解--> 11 <aop:aspectj-autoproxy/> 12 </beans>
編寫測試類代碼
1 public class App 2 { 3 public static void main( String[] args ) 4 { 5 ApplicationContext ac=new ClassPathXmlApplicationContext("/applicationContext.xml"); 6 DoSome bean = ac.getBean("dosome",DoSome.class); 7 bean.dosome(); 8 //bean.error(); 9 } 10 }
后續補充純注解配置方式,更方便一些