Advice切面介面
package aop;import java.lang.reflect.Method;public interface Advice {void beforeMethed(Method method);void afterMethed(Method method);}MyAdvice切面實作類別
package aop;import java.lang.reflect.Method;public class MyAdvice implements Advice {private long beginTime=0;@Overridepublic void beforeMethed(Method method) {beginTime=System.currentTimeMillis();System.out.println("before method:"+method.getName());}@Overridepublic void afterMethed(Method method) {long endTime=System.currentTimeMillis();System.out.println("end method:"+method.getName()+" method use "+String.valueOf(endTime-beginTime)+" millisecond");}}代理工廠
package aop;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class ProxFactoryBean {private Object target;private Advice advice;public Object getProx(){Object prox= Proxy.newProxyInstance(target.getClass().getClassLoader(),//類載入器 target.getClass().getInterfaces(), //目標對象的介面new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method, Object[] args) throws Throwable {advice.beforeMethed(method);//調用目標之前Object resVal= method.invoke(target, args);//調用目標advice.afterMethed(method);//調用目標之後return resVal;}});return prox;//這裡放回的是目標對象的介面,所以調用的時候也要用介面}public void setTarget(Object target) {this.target = target;}public void setAdvice(Advice advice) {this.advice = advice;}}
Bean工廠
package aop;import java.io.IOException;import java.io.InputStream;import java.util.Properties;public class BeanFactory {private Properties properties=new Properties();public BeanFactory(InputStream inStream) throws IOException {properties.load(inStream);}public Object getBean(String beanName) {String className=properties.getProperty(beanName);//到設定檔中尋找bean的全路徑Object bean=null;try {bean = Class.forName(className).newInstance();//執行個體化Bean} catch (Exception e) {e.printStackTrace();} if(bean instanceof ProxFactoryBean){//如果Bean是代理對象ProxFactoryBean proxFactoryBean=(ProxFactoryBean)bean;//擷取代理對象try {Advice advice = (Advice) Class.forName(properties.getProperty(beanName +".advice")).newInstance();Object target=Class.forName(properties.getProperty(beanName +".target")).newInstance();proxFactoryBean.setAdvice(advice);//設定切面proxFactoryBean.setTarget(target);//設定代理那個對象} catch (Exception e) {e.printStackTrace();}return proxFactoryBean.getProx();}return bean;}}
設定檔
#xxx=java.util.ArrayListxxx=aop.ProxFactoryBeanxxx.advice=aop.MyAdvicexxx.target=java.util.ArrayList
測試類別
package aop;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;public class AopMain {/** * @param args * @throws IOException */public static void main(String[] args) throws IOException {BeanFactory factory=new BeanFactory(AopMain.class.getResourceAsStream("bean.properties"));Collection list=(Collection) factory.getBean("xxx");//這裡要用介面list.add("a");System.out.println(list.size());}}