1.目标类及方法:
package com.proxy2;
public class UserManagerImpl implements UserManager {
@Override
public void addUser() {
// TODO Auto-generated method stub
System.out.println("***addUser***");
}
@Override
public void delUser() {
// TODO Auto-generated method stub
System.out.println("****delUser***");
}
}
2。需要插入的代码;
public class SecurityHandler {
public void beforeSecurity(){
System.out.println("*****checkSecurity before******");
}
public void afterSecurity(){
System.out.println("*****checkSecurity after******");
}
}
3。spring配置文件配置如下:
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aophttp://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<aop:config>
<aop:aspect id="secAspect" ref="sec">
<aop:pointcut id="addAddMethod" expression="execution(* add*(..))"/> <!--定义执行addUser等方法时候触发-->
<aop:before method="beforeSecurity" pointcut-ref="addAddMethod"/>
<aop:after method="afterSecurity" pointcut-ref="addAddMethod"/>
</aop:aspect>
</aop:config>
<bean id="userManager" class="com.proxy2.UserManagerImpl"/>
<bean id="sec" class="com.proxy2.SecurityHandler"/>
</beans>
4。[补充] aop支持带参数形式(在advice获得参数名称,方法名称等等):
修改如下 public void addUser(String name,String age) {
// TODO Auto-generated method stub
System.out.println("***addUser***");
}
public void beforeSecurity(JoinPoint joinPoint){
for(int i=0;i<joinPoint.getArgs().length;i++){
System.out.println(joinPoint.getArgs()[i]); ---打印参数名称
}
System.out.println(joinPoint.getSignature().getName()); --打印方法名称
System.out.println("*****checkSecurity before******");
}