配置文件java
<?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/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 激活組件掃描功能,在包cn.ysh.studio.spring.aop及其子包下面自動掃描經過註解配置的組件 --> <context:component-scan base-package="com.zhiguoguo.service,aspect"/> <!-- 激活自動代理功能 --> <aop:aspectj-autoproxy proxy-target-class="true"/> </beans>
service類:spring
package com.zhiguoguo.service; import org.springframework.stereotype.Component; @Component public class HelloService { public String sayHello() { System.out.println("——————方法執行——————"); // throw new RuntimeException("haha"); return "Hello world!"; } }
切面AOP:函數
package com.zhiguoguo.aspect; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; /** * 定義切面 */ @Component @Aspect public class HelloServiceAspect { @Before("execution(* com.zhiguoguo.service.HelloService.*(..))") public void authorith(){ System.out.println("模擬進行權限檢查。"); } @After("execution(* com.zhiguoguo.service.HelloService.*(..))") public void release() { System.out.println("模擬方法結束後的釋放資源..."); System.out.println(); } @AfterReturning(returning="obj", pointcut="execution(* com.zhiguoguo.service.HelloService.*(..))") public void log(Object obj) { System.out.println("模擬目標方法返回值:" + obj); System.out.println("模擬記錄日誌功能..."); System.out.println(); } @AfterThrowing(throwing="ex", pointcut="execution(* com.zhiguoguo.service.HelloService.*(..))") public void doRecoverActions(Throwable ex) { System.out.println("目標方法中拋出的異常:" + ex); System.out.println("模擬拋出異常後的加強處理..."); } // @Around("execution(* com.zhiguoguo.service.HelloService.*(..))")//這裏先註釋掉 public Object processTx(ProceedingJoinPoint jp) throws java.lang.Throwable { System.out.println("執行目標方法以前,模擬開始事物..."); // 執行目標方法,並保存目標方法執行後的返回值 Object rvt = jp.proceed(); //這裏的切面方法若是有參數才能傳遞一個參數給他 // Object rvt = jp.proceed(new String[]{"被改變的參數"}); System.out.println("執行目標方法以前,模擬結束事物..."); System.out.println(); //通過這麼一個環繞,能夠加強返回值 return rvt + "新增的內容"; } }
主函數:spa
package main; import com.zhiguoguo.service.HelloService; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class HelloApp { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml"); HelloService helloService = context.getBean(HelloService.class); helloService.sayHello(); } }