定义切面类:
public class SecurityHandler {
private void checkSecurity() {
System.out.println("----------checkSecurity()---------------");
}
}
配置文件中这样子写:
<?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-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<bean id="securityHandler" class="com.bjsxt.spring.SecurityHandler"/>
<bean id="userManager" class="com.bjsxt.spring.UserManagerImpl"/>
<aop:config>
<aop:aspect id="security" ref="securityHandler">
<aop:pointcut id="allAddMethod" expression="execution(* add*(..))"/>
<aop:before method="checkSecurity" pointcut-ref="allAddMethod"/>
</aop:aspect>
</aop:config>
</beans>
测试:
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
UserManager userManager = (UserManager)factory.getBean("userManager");
userManager.addUser("张三", "123");
userManager.deleteUser(1);
}
这样就可以在调用addUser之前执行checkSecurity方法了
如果我们需要获得add*(..)的传入的参数
可以通过Advice中添加一个JoinPoint参数,这个值会由spring自动传入,从JoinPoint中可以取得
参数值、方法名等等
如下:修改SecurityHandler 类
import org.aspectj.lang.JoinPoint;
public class SecurityHandler {
private void checkSecurity(JoinPoint joinPoint) {
Object[] args = joinPoint.getArgs();//获得addUser中传入的参数
for (int i=0; i<args.length; i++) {
System.out.println(args[i]);//打印出addUser中传入的参数,这里是张三和123
}
System.out.println(joinPoint.getSignature().getName());//获得被调用的方法名,这里是打印出addUser
System.out.println("----------checkSecurity()---------------");
}
}