基于代理的spring aop中目标对象引入新特性的实现

版权声明:仅供学习交流使用 https://blog.csdn.net/drxRose/article/details/84841523

IntroductionInterceptor也是一个标记接口,其子类中有个便捷的实现类,即DelegatingIntroductionInterceptor.

说明,定义引入的实现类,也需要实现新增特性的接口.


目标对象类

package siye;
public class TargetObj
{
	public void targetMeth()
	{
		System.out.println("target_object_method....");
	}
}

新增特性接口

package siye;
public interface NewFeature
{
	void featureMeth();
}

引入实现类

package siye;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
public class IntroductionInterceptorImpl extends
		DelegatingIntroductionInterceptor implements NewFeature
{// 实现引入接口的同时,也要实现新增特性的接口.
	private static final long serialVersionUID =
			-5595327221312353940L;
	@Override
	public Object invoke(MethodInvocation mi) throws Throwable
	{
		return super.invoke(mi);
	}
	@Override
	public void featureMeth()
	{
		System.out.println("new_feature_method...");
	}
}

测试基于代理的spring aop引入功能的测试类

package siye;
import org.aopalliance.aop.Advice;
import org.springframework.aop.framework.ProxyFactory;
public class UnitTest
{
	public static void main(String[] args)
	{
		TargetObj targetObj = new TargetObj();
		Advice adviceImpl = new IntroductionInterceptorImpl();
		ProxyFactory proxy = new ProxyFactory();
		// 设置cglib代理,否则无法对目标类进行动态代理.
		proxy.setProxyTargetClass(true);
		proxy.addAdvice(adviceImpl);
		proxy.setTarget(targetObj);
		TargetObj obj0 = (TargetObj) proxy.getProxy();
		obj0.targetMeth();
		NewFeature obj1 = (NewFeature) obj0;
		obj1.featureMeth();
	}
}

猜你喜欢

转载自blog.csdn.net/drxRose/article/details/84841523