Spring AOP 初探 (二)

2014-11-24 11:49:45 · 作者: · 浏览: 17
..");
}

}

package org.spring.tutorial;

import java.lang.reflect.Method;

import org.springframework.aop.MethodBeforeAdvice;

/**
* 安全控制类
*
*/
public class SafeControl implements MethodBeforeAdvice {

@Override
public void before(Method method, Object[] args, Object target)
throws Throwable {
System.out.println("判断是否为管理员...");
}

}
该类的方法before会在注册和注销方法调用前被调用。
然后编写Spring的配置文件:
[html]
< xml version="1.0" encoding="UTF-8" >
http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">





class="org.springframework.aop.framework.ProxyFactoryBean">



safeControl



< xml version="1.0" encoding="UTF-8" >
http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">





class="org.springframework.aop.framework.ProxyFactoryBean">



safeControl




最后编写测试类:
[java]
package org.spring.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"SpringConfig.xml"});
RegisterSystem proxy = (RegisterSystem) context.getBean("registerSystemProxy");
proxy.register("benson");
proxy.unRegister("benson");
}
}

package org.spring.tutorial;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"SpringConfig.xml"});
RegisterSystem proxy = (RegisterSystem) context.getBean("registerSystemProxy");
proxy.register("benson");
proxy.unRegister("benson");
}
}
运行一下:
[plain]
判断是否为管理员...
会员:benson注册成功!
判断是否为管理员...
会员:benson注销成功!

判断是否为管理员...
会员:benson注册成功!
判断是否为管理员...
会员:benson注销成功!
在每次调用注册或者注销方法时,首先会进行安全控制。
总结:
通过AOP,我们可以将系统功能,如日志记录,事务管理,安全控制,审计等从方法中解脱出来,这样方法可以专注于核心的业务逻辑,大大增加了系统的可维护性。
其它:
项目结构:



如果IDE提示“The hierarchy of the type MyBeforeMethod is inconsistent”,说明缺少了一个jar包 - aopalliance jar