首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

spring对AOP的支持(采取配置文件的方式)

2012-11-04 
spring对AOP的支持(采用配置文件的方式)定义切面类:public class SecurityHandler {private void checkSec

spring对AOP的支持(采用配置文件的方式)
定义切面类:

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" 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());//获得被调用的方法名,这里是打印出addUserSystem.out.println("----------checkSecurity()---------------");}}

热点排行