java Proxy 解析---spring aop

落日映苍穹つ 2021-09-21 01:46 267阅读 0赞

1.接口

  1. public interface IAccountService {
  2. int getInt(int i);
  3. int getInt2(int i);
  4. }

2.实现

  1. public class AccountServiceImpl implements IAccountService {
  2. public int getInt(int i) {
  3. return i;
  4. }
  5. public int getInt2(int i) {
  6. return i;
  7. }
  8. }

3.代理类

  1. package com.jd.xq.proxy;
  2. import com.jd.xq.service.IAccountService;
  3. import java.lang.reflect.InvocationHandler;
  4. import java.lang.reflect.Method;
  5. /** * @author duanxiaoqiu * @Date 2020-01-07 16:21 **/
  6. public class AccountAdvice implements InvocationHandler {
  7. private IAccountService iAccountService;
  8. public AccountAdvice(IAccountService iAccountService) {
  9. this.iAccountService = iAccountService;
  10. }
  11. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  12. if (method.getName().equals("getInt")) {
  13. return 100;
  14. }
  15. return method.invoke(iAccountService, args);
  16. }
  17. }

4.应用

  1. public static void main(String[] args) {
  2. //创建目标对象
  3. IAccountService target = new AccountServiceImpl();
  4. //创建代理对象
  5. IAccountService proxy = (IAccountService) Proxy.newProxyInstance(target.getClass().getClassLoader(),
  6. target.getClass().getInterfaces(),
  7. new AccountAdvice(target)
  8. );
  9. System.out.println(proxy.getInt(1));
  10. System.out.println(proxy.getInt2(1));
  11. }

发表评论

表情:
评论列表 (有 0 条评论,267人围观)

还没有评论,来说两句吧...

相关阅读