接口:
public interface Api {
public String run(String param);
}
实现类:
public class Target implements Api {
@Override
public String run(String param) {
System.out.println("被代理的方法");
return "这是一个返回值";
}
}
xml配置方式:
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<bean id="target" class="com.zwk.aop.Target"/>
<bean id="advice" class="com.zwk.aop.Advice"/>
<aop:config>
<aop:aspect id="test" ref="advice">
<aop:pointcut expression="execution( * com.zwk.aop.Target.*(..)) "
id="myPointcut"/>
<aop:around pointcut-ref="myPointcut" method="around"/>
<aop:after pointcut-ref="myPointcut" method="after"/>
<aop:after-returning method="afterReturning" pointcut-ref="myPointcut" returning="returning"/>
<!-- 有参数的方法pointcut配置 -->
<aop:before method="before" pointcut="execution( * com.zwk.aop.Target.*(..)) and args(param)"/>
</aop:aspect>
</aop:config>
</beans>
注解的配置方式(使用注解配置时去掉xml文件中的aop命名空间内容,再加上 <aop:aspectj-autoproxy/>):
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class Advice {
@Pointcut("execution(* com.zwk..*(..))")
public void template(){}
//有参数的情况
@Before("template()&&args(param)")
public void before(String param){
System.out.println("参数:"+param);
System.out.println("调用方法之前");
}
@After("template()")
public void after(){
System.out.println("调用方法之后");
}
@AfterReturning(value="template()",returning="returning")
public void afterReturning(JoinPoint pj,Object returning){
System.out.println("参数:"+pj.getArgs()[0]);
System.out.println("方法返回之后");
System.out.println("返回值:"+returning);
}
@Around("template()")
public Object around(ProceedingJoinPoint pjp){
System.out.println("前置环绕通知");
Object val=new Object();
try {
val=pjp.proceed();
System.out.println("返回值:"+val);
} catch (Throwable e) {
e.printStackTrace();
}
System.out.println("后置环绕通知");
return val;
}
}
测试代码:
public class Demo {
public static void main(String[] args) {
ApplicationContext applicationContext=new ClassPathXmlApplicationContext("beans.xml");
((Api)applicationContext.getBean("target")).run("这是一个参数");
}
}
所需 jar包: