简单自定义AOP实现

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yaonga/article/details/83023522

自定义实现AOP动态代理(动态代理,反射)

AOP是什么

  • 面向切面编程,是一种思想

AOP解决了什么

  • 对已有类进行功能增强

AOP自定义

  • 定义代理实现类ProxyFactoryBean
 public class ProxyFactoryBean {
			public Object getTarget() {
				return target;
			}
			public void setTarget(Object target) {
				this.target = target;
			}
			public Advice getAdvice() {
				return advice;
			}
			public void setAdvice(Advice advice) {
				this.advice = advice;
			}
			private Object target;
			private Advice advice;
			public Object getProxy()
			{
					return        Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() {
						
						public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
							advice.before();
							Object invoke = method.invoke(target, args);
							advice.after();
							return invoke;
						}
					});
				}
			  }
  • 添加增强类MyAdvice

      public interface Advice {
    
      public void before();
      
      public void after();
      }
    
      public class MyAdvice implements Advice{
    
      public void before() {
      	System.out.println("开始学习");
      }
    
      public void after() {
      	System.out.println("结束学习");
      }
      }
    
  • 加载配置文件获取代理对象FactoryBean

public class FactoryBean {
	  	Properties ps = new Properties();
	  	public FactoryBean(InputStream ips)
	  	{
	  		try {
				ps.load(ips);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	  	}
		public Object getBean(String name) {
		    Object bean = null;
			try {
				Class<?> clazz = Class.forName(ps.getProperty(name));
				bean = clazz.newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
			if(bean instanceof ProxyFactoryBean)
			{
				ProxyFactoryBean proxy = (ProxyFactoryBean)bean;
				Object target = null;
				Advice advice = null;
				try {
					target = Class.forName(ps.getProperty(name+".target")).newInstance();
					advice = (Advice) Class.forName(ps.getProperty(name+".advice")).newInstance();
				} catch (Exception e) {
					e.printStackTrace();
				} 
				proxy.setTarget(target);
				proxy.setAdvice(advice);
				bean = proxy.getProxy();
			}
			
			return bean;
		}
	   }

  • 应用测试类App
		public class App 
		{
		    public static void main( String[] args ) throws Exception
		    {
		        //System.out.println( "Hello World!" );
		    	InputStream ips = App.class.getClassLoader().getResourceAsStream("config.properties");
		    	FactoryBean factory = new FactoryBean(ips);
		    	factory.getBean("xxx");
		    }
		}
  • 配置文件config.properties
	    #xxx=java.util.ArrayList
		xxx=com.yalong.proxy.ProxyFactoryBean
		xxx.target=java.util.ArrayList
		xxx.advice=com.yalong.proxy.MyAdvice

总结

  • 使用jdk动态代理对目标类进行代理
  • 定义增强类接口,对代理对象进行代码横向切入
  • 加载配置文件,反射获取实例

猜你喜欢

转载自blog.csdn.net/yaonga/article/details/83023522