前置通知( Advice):在方法调用前自定义操作。比如方法调用时的log记录、计时、登陆验证等。下面的是AOP中前置通知的例子:(使用较多的)
附:前置通知的代码:
package com.springTest.AOP;
public class TestBean {
public void writerSecureMessge(){
System.out.println("the method is do something!");
}
}
应用操作类
package com.springTest.AOP;
import java.util.ArrayList;
import java.util.List;
public class LoginSerivce {
private static List isLoginlist = new ArrayList();
public void Login(String username){
//验证都通过
isLoginlist.add(username);
}
public void logout(String username){
if(isLoginlist.contains(username)){
isLoginlist.remove(username);
}
}
public List getLogedOnUser(){
return isLoginlist;
}
}
通知类Advice
package com.springTest.AOP;
import java.lang.reflect.Method;
import java.util.List;
import org.springframework.aop.MethodBeforeAdvice;
public class LoginAdvice implements MethodBeforeAdvice {
private LoginSerivce loginserivce;
public LoginAdvice(){
loginserivce = new LoginSerivce();
}
public void before(Method method, Object[] arg1, Object arg2)
throws Throwable {
List loginlist = loginserivce.getLogedOnUser();
if(loginlist!=null&&loginlist.size()==0){
System.out.println("no user is login!");
throw new SecurityException("you must login before the method:"+method.getName());
}else if(loginlist.contains("zzy")){
System.out.println("user is passed!");
}else {
System.out.println("user is not good!");
throw new SecurityException("you is not allowed access to method:"+method.getName());
}
}
}
主测试类
package com.springTest.AOP;
import org.springframework.aop.framework.ProxyFactory;
public class TestLogin {
public static void main(String[] args) {
String username = "zzy";
String errorname = "youzi";
TestBean test = getTestBean(); //要执行的方法
LoginSerivce serivce = new LoginSerivce();
serivce.Login(username);
test.writerSecureMessge();
serivce.logout(username);
try{
serivce.Login(errorname); //名字不对的情况
test.writerSecureMessge();
}catch(SecurityException e){
System.out.println("Exception Caught:"+e.getMessage());
}finally{
serivce.logout(errorname);
}
try{
test.writerSecureMessge(); //没有登陆的情况
}catch(SecurityException e){
System.out.println("Exception Caught:"+e.getMessage());
}
}
private static TestBean getTestBean(){
TestBean bean = new TestBean();
//获取advice
LoginAdvice advice = new LoginAdvice();
//获取代理proxy
ProxyFactory factory = new ProxyFactory();
factory.setTarget(bean);
factory.addAdvice(advice);
TestBean proxy = (TestBean) factory.getProxy();
return proxy;
}
}
执行后输出:
- CGLIB2 available: proxyTargetClass feature enabled
- Commons Collections 3.x available
user is passed!
the method is do something! ---通过了
user is not good! ---在通知中终止了非法操作
Exception Caught:you is not allowed access to method:writerSecureMessge
no user is login! ---在通知中终止了非法操作
Exception Caught:you must login before the method:writerSecureMessge