AspectJ Aop 面向切面

来源:互联网 发布:淘宝小卖家死了大半 编辑:程序博客网 时间:2024/05/21 16:16
依赖包:
需要依赖包
如果是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形式的。
0 0
原创粉丝点击