bean.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"
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">
<bean id="tableServiceImpl" class="com.baidu.impl.TableServiceImpl"></bean>
<bean id="myAspect" class="com.baidu.service.MyAspect"></bean>
<aop:config>
<aop:aspect ref="myAspect">
<aop:pointcut expression="execution(* com.baidu.impl..add*(..))" id="point1"/>
<aop:before method="myBefore" pointcut-ref="point1"/>
<aop:after-returning method="myAfterReturning" pointcut-ref="point1" returning="result"/>
<aop:around method="myAround" pointcut-ref="point1" />
<aop:after-throwing method="myAfterThrowing" pointcut-ref="point1" throwing="ex"/>
</aop:aspect>
</aop:config>
</beans>
编写被代理对象
public interface TableServiceI {
void delete();
String add();
}
public class TableServiceImpl implements TableServiceI{
@Override
public void delete() {
System.out.println("delete");
}
@Override
public String add() {
System.out.println("add");
return "add";
}
}
编写增强的代码
public class MyAspect {
public void myBefore(JoinPoint joinPoint) {
System.out.println("前置增强"+joinPoint.toString());
}
public void myAfterReturning(JoinPoint joinPoint,Object result) {
System.out.println("后置增强,返回值"+result);
}
public void myAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("环绕通知1");
Object proceed = joinPoint.proceed();
System.out.println("环绕通知2,返回值"+joinPoint);
}
public void myAfterThrowing(JoinPoint joinPoint,Exception ex){
System.out.println("异常了,,,"+ex.getMessage());
}
}