无配置文件实现spring aop

import java.lang.reflect.Method;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ceshi{

public static void main(String args[]){
	
	AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext("test");//我个人认为这相当于容器
	Exetor exetor=new Exetor();
	Record record=new Record();
	JdkRegexpMethodPointcut jdk=new JdkRegexpMethodPointcut();
	jdk.setPattern(".*record");
	DefaultPointcutAdvisor pointcut=new DefaultPointcutAdvisor();
	pointcut.setAdvice(record);
	pointcut.setPointcut(jdk);
	ProxyFactoryBean proxy=new ProxyFactoryBean();
	proxy.setBeanFactory(ac.getBeanFactory());
	ac.getBeanFactory().registerSingleton("exetor", exetor);
	ac.getBeanFactory().registerSingleton("pointcut", pointcut);//这个相当于创造bean
	proxy.setTarget(ac.getBean(Exetor.class));
	proxy.setInterceptorNames("pointcut");
	
	try{
	proxy.setProxyInterfaces(Log.class.getInterfaces());}
	catch(Exception e){
		
	}
	ac.getBeanFactory().registerSingleton("proxy", proxy);
	Log log=(Log)ac.getBean("proxy");
	log.record();
}

}
interface Log{
	void record();
}

class Exetor implements Log{
	public void record(){
		System.out.println("运行");
	}
	
}


 
class Record implements MethodBeforeAdvice,AfterReturningAdvice{
	@Override
	public void before(Method arg0,Object[] arg1,Object arg2){
		System.out.println(System.currentTimeMillis());
	}
	@Override
	public void afterReturning(Object arg0,Method arg1,Object[] arg2,Object arg3) throws Throwable{
		System.out.println(System.currentTimeMillis());
		
	}
}
经验分享 程序员 微信小程序 职场和发展