ProxyFactory 是 Spring AOP的实现方式之一。下面介绍下ProxyFactory的用法。
1、接口定义
public interface UserReadService { public UserInfo getUserInfoById(Long id); }
2、接口实现
public class UserReadServiceImpl implements UserReadService { @Override public UserInfo getUserInfoById(Long id) { System.out.println("获取用户信息"); return null; } }
3、拦截器定义
public class UserInterceptor implements MethodInterceptor { @Override public Object invoke(MethodInvocation invocation) throws Throwable { System.out.println("start"); Object obj = invocation.proceed(); System.out.println("end"); return obj; } }
4、测试
public static void main(String[] args) { ProxyFactory factory = new ProxyFactory(new UserReadServiceImpl()); factory.addAdvice(new UserInterceptor()); UserReadService userReadService = (UserReadService) factory.getProxy(); userReadService.getUserInfoById(null); }
结果:
start
获取用户信息
end