Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create proxy without using spring AOP

Tags:

java

spring

aop

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

like image 571
Mangoose Avatar asked Apr 12 '13 11:04

Mangoose


People also ask

Is Spring AOP proxy-based?

Spring AOP is proxy-based. It is vitally important that you grasp the semantics of what that last statement actually means before you write your own aspects or use any of the Spring AOP-based aspects supplied with the Spring Framework.

How many types of proxy are there in Spring Framework?

Spring used two types of proxy strategy one is JDK dynamic proxy and other one is CGLIB proxy. JDK dynamic proxy is available with the JDK.

What is a proxy in AOP?

AOP proxy: an object created by the AOP framework in order to implement the aspect contracts (advise method executions and so on). In the Spring Framework, an AOP proxy will be a JDK dynamic proxy or a CGLIB proxy. Weaving: linking aspects with other application types or objects to create an advised object.


1 Answers

An example using a Spring bean post-processor to proxy every 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();
        }
    }
}
like image 198
rees Avatar answered Sep 21 '22 13:09

rees