spring 结合proxy代理模式

2021-07-02  本文已影响0人  程序男保姆

public interface Ido {

    public String login (String l);
    public String mes (String l);

}


import org.springframework.stereotype.Service;

@Service(value = "jdDoImpl")
public class JDDoImpl implements Ido {
    @Override
    public String login(String l) {
        return "JD login = " + l;
    }

    @Override
    public String mes(String l) {
        return "JD mes = " + l;
    }
}

@Service(value = "zssDoImpl")
public class ZssDoImpl implements Ido {
    @Override
    public String login(String l) {
        return "Zss login = " + l;
    }

    @Override
    public String mes(String l) {
        return "Zss mes = " + l;
    }
}


@Component
public class IdoInvocationHandleProxy<T> implements InvocationHandler {

    public <T> T newInstance(Class<T> clz) {
        return (T) Proxy.newProxyInstance(clz.getClassLoader(), new Class[] { clz }, this);
    }

    /**
     * proxy:代表动态代理对象
     * method:代表正在执行的方法
     * args:代表调用目标方法时传入的实参
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                // 诸如hashCode()、toString()、equals()等方法,将target指向当前对象this
                Object invoke = method.invoke(this, args);
                return invoke;
            } catch (Throwable t) {
            }
        }
        System.out.println("执行之前");

        T t = (T) SpringContextUtils.getBean(args[0].toString());

        Object invoke = method.invoke(t, args);
        System.out.println("执行之后");
        return invoke;
    }
}

@Configuration
public class Config {
    @Bean
    public Ido ido() {
        IdoInvocationHandleProxy<Ido> idoIdoInvocationHandle = new IdoInvocationHandleProxy<>();
        Ido ido = idoIdoInvocationHandle.newInstance(Ido.class);
        return ido;
    }
}

@RestController
@RequestMapping("/t")
public class TestController {

    @Resource
    Ido ido;

    @RequestMapping("/login")
    public String login (String s){
        String login = ido.login(s);
        return login;
    }


}

上一篇下一篇

猜你喜欢

热点阅读