1. 程式人生 > >AspectJ Aop 面向切面

AspectJ Aop 面向切面

依賴包: 需要依賴包 如果是maven管理專案的,直接pom檔案裡面依賴就可以了,如果是手動下載jar檔案的需要下載aspectjtools.jar <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjtools</artifactId> <version>1.6.10</version> </dependency> xml形式的 在spring的配置檔案applicationContext.xml檔案中新增aop <?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="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.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd 
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"
default-autowire="byName">
 <aop:config>  
        <aop:aspect id="servicesAop" ref="aspectBean">  
            <!-- 配置com.pinganfu包下所有類或介面的所有方法   -->
            <aop:pointcut id="businessService" expression="execution(* com.test.*.*(..))" /> 
            <aop:before pointcut-ref="businessService" method="doBefore"/>  
            <aop:after pointcut-ref="businessService" method="doAfter"/>
            <aop:around pointcut-ref="businessService" method="doAround"/>  
        <aop:after-returning pointcut-ref="businessService" method="afterReturning" returning="retval" arg-names="joinPoint,retval"/>
            <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>  
        </aop:aspect>  
    </aop:config>  
    <bean id="aspectBean" class="com.test.AopTest /> 
</beans> java類: import java.net.InetAddress; import java.net.UnknownHostException; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.ProceedingJoinPoint; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /**  *   */ public class AopTest{ public void doBefore(JoinPoint jp) { System.out.println("執行方法前"); } public Object doAround(ProceedingJoinPoint pjp) throws Throwable { System.out.println("執行方法"); } public void doAfter(JoinPoint jp) { System.out.println("執行方法後"); } public void afterReturning(JoinPoint joinPoint, String retVal) { System.out.println("返回值"); } public void doThrowing(JoinPoint jp, Throwable ex) { System.out.println("產生異常"); } } 以上就是xml形式的。