7

My server doesn't have spring AOP jars and I can't add them. Spring version is 2.0.6.

I want to use proxy for 5 of my services.

What is the best way to do this

4

3 回答 3

1

看看java.lang.reflect.ProxyAPI。请注意,它只允许为接口创建代理。

于 2013-04-12T11:13:22.823 回答
1

使用 Spring bean 后处理器代理每个 bean 的示例:

public class ProxifyingPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {

        Class beanClass = bean.getClass();

        if (Proxy.isProxyClass(beanClass)) {
            return bean;
        }

        List<Class<?>> interfaceList = getAllInterfaces(beanClass);
        Class[] interfaces = (interfaceList.toArray(new Class[interfaceList.size()]));

        return Proxy.newProxyInstance(beanClass.getClassLoader(), interfaces, new InvocationHandler() {

            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                return method.invoke(bean, objects);
            }

        });
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    private List<Class<?>> getAllInterfaces(Class<?> cls) {
        if (cls == null) {
            return null;
        }
        LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<Class<?>>();
        getAllInterfaces(cls, interfacesFound);
        return new ArrayList<Class<?>>(interfacesFound);
    }

    private void getAllInterfaces(Class<?> cls, HashSet<Class<?>> interfacesFound) {
        while (cls != null) {
            Class<?>[] interfaces = cls.getInterfaces();
            for (Class<?> i : interfaces) {
                if (interfacesFound.add(i)) {
                    getAllInterfaces(i, interfacesFound);
                }
            }
            cls = cls.getSuperclass();
        }
    }
}
于 2013-04-23T00:55:08.133 回答
1

您可以实现动态代理或 CGLib 代理。

于 2013-04-12T11:55:59.340 回答