#spring自定义代理类
定义接口
/**
* @author jin
*/
public interface TestService {
List<String> getList(String code, String name);
}
定义代理工厂
@Component
public class ServiceProxyFactory implements FactoryBean<TestService>{
@Override
public TestService getObject() {
Class<?> interfaceType = TestService.class;
InvocationHandler handler = new ServiceInvocationHandler(interfaceType);
return (TestService) Proxy.newProxyInstance(interfaceType.getClassLoader(),
new Class[] {interfaceType},handler);
}
@Override
public Class<?> getObjectType() {
return TestService.class;
}
@Override
public boolean isSingleton() {
return true;
}
}
定义代理处理器
public class ServiceInvocationHandler implements InvocationHandler {
private Class<?> interfaceType;
public ServiceInvocationHandler(Class<?> intefaceType) {
this.interfaceType = interfaceType;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
System.out.println("if调用前");
return method.invoke(this,args);
}
System.out.println("调用前,参数:{}" + args);
Object result = Arrays.asList(args);
System.out.println("调用后,结果:{}" + result);
return result;
}
}