接口
package net.blogjava.dodoma.spring.aop;
public interface HelloI {
?public String sayHello(String firstName,String lastName);
?}
實(shí)現(xiàn)類
package net.blogjava.dodoma.spring.aop;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Hello implements HelloI {
?protected static final Log log=LogFactory.getLog(Hello.class);
?private String msg;
?public Hello(){}
?public Hello(String msg){
??this.msg=msg;
?}
?public String getMsg() {
??return msg;
?}
?public void setMsg(String msg) {
??this.msg = msg;
?}
?public String sayHello(String firstName, String lastName) {
??// TODO Auto-generated method stub
??log.info("in the class "+this.getClass().getName()+"'s method sayHello()");
??return (msg+" "+firstName+" "+lastName);
?}
}
BeforeAdvice通知
package net.blogjava.dodoma.spring.aop;
import java.lang.reflect.Method;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.MethodBeforeAdvice;
/**
?* 方法調(diào)用之前.
?* 先調(diào)用此方法
?* @author dodoma
?**/
public class LogBeforeAdvice implements MethodBeforeAdvice {
?protected static final Log log = LogFactory.getLog(LogBeforeAdvice.class);
?public void before(Method m, Object[] args, Object target) throws Throwable {
??log.info("in the class "+this.getClass().getName()+"'s method before()");
??log.info("the target class is:" + target.getClass().getName());
??log.info("the target method is:" + m.getName());
??for (int i = 0; i < args.length; i++) {
???log.info("the method's args is:" + args[i]);
??}
??//測(cè)試,如果在before通知中發(fā)生了異常,程序流程將如何
??//throw new Exception("異常");
?}
}
測(cè)試類
package net.blogjava.dodoma.spring.aop;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class HelloTest {
?protected static final Log log = LogFactory.getLog(HelloTest.class);
?public static void main(String[] args) throws Exception {
??// TODO Auto-generated method stub
?//應(yīng)用spring的ioc容器
??Resource rs = new ClassPathResource("beans.xml");
??BeanFactory bf = new XmlBeanFactory(rs);
??HelloI h = (HelloI) bf.getBean("theBean");
??log.info("starting...");
??try {
???log.info(h.sayHello("ma", "bin"));
?????} catch (Exception e) {
???e.printStackTrace();
??}
??log.info("end...");
??
??//如果沒(méi)有使用spring的ioc,可以直接用如下代碼測(cè)試
??ProxyFactory factory=new ProxyFactory();
??factory.addAdvice(new LogBeforeAdvice());//添加通知
??factory.setTarget(new Hello("hello"));//添加被代理的類實(shí)例
??try{
??HelloI hi=(HelloI)factory.getProxy();
??hi.sayHello("ma","bin");}
??catch(Exception e){e.printStackTrace();}
?}
}