Java/Spring/Spring Aspect

Материал из Java эксперт
Перейти к: навигация, поиск

After Advice Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

////////////////////////////////////////////////////////
import java.util.Random;
public class KeyGenerator {
    public static final long WEAK_KEY = 0xFFFFFFF0000000L;
    public static final long STRONG_KEY = 0xACDF03F590AE56L;
    
    public long getKey() {
        Random rand = new Random();
        int x = rand.nextInt(3);
        
        if(x == 1) {
            return WEAK_KEY;
        } else {
            return STRONG_KEY;
        }
    }
}

////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
public class WeakKeyCheckAdvice implements AfterReturningAdvice {
    public void afterReturning(Object returnValue, Method method,
            Object[] args, Object target) throws Throwable {
        if ((target instanceof KeyGenerator)
                && ("getKey".equals(method.getName()))) {
            long key = ((Long) returnValue).longValue();
            if (key == KeyGenerator.WEAK_KEY) {
                throw new SecurityException(
                        "Key Generator generated a weak key. Try again");
            }
        }
    }
}
////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;
public class AfterAdviceExample {
    public static void main(String[] args) {
        KeyGenerator keyGen = getKeyGenerator();
        
        for(int x = 0; x < 10; x++) {
            try {
                long key = keyGen.getKey();
                System.out.println("Key: " + key);
            } catch(SecurityException ex) {
                System.out.println("Weak Key Generated!");
            }
        }
        
    }
    
    private static KeyGenerator getKeyGenerator() {
        
        KeyGenerator target = new KeyGenerator();
        
        ProxyFactory factory = new ProxyFactory();
        factory.setTarget(target);
        factory.addAdvice(new WeakKeyCheckAdvice());
        
        return (KeyGenerator)factory.getProxy();
    }
}





Aspect Hello World Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public interface IMessageWriter {
    public void writeMessage();
}

///////////////////////////////////////////////////////////////////////////////////////

public class MessageWriter implements IMessageWriter{
    public void writeMessage() {
        System.out.print("World");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;

public class MessageDecorator implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.print("Hello ");
        Object retVal = invocation.proceed();
        System.out.println("!");
        return retVal;
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;
public class HelloWorldAOPExample {
    public static void main(String[] args) {
        MessageWriter target = new MessageWriter();
        
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.addAdvice(new MessageDecorator());
        pf.setTarget(target);

        MessageWriter proxy = (MessageWriter) pf.getProxy();
        
        // write the messages
        target.writeMessage();
        System.out.println("");
        proxy.writeMessage();
    }
}





AspectJ Example from Pro Spring

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/





Composable Pointcut Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
//////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class SimpleBeforeAdvice implements MethodBeforeAdvice {

    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("Before method: " + method);
    }
}

//////////////////////////////////////////////////////////////////////////////////
public class SampleBean {
    public String getName() {
        return "Rob Harrop";
    }
    
    public void setName(String name) {
        
    }
    
    public int getAge() {
        return 100;
    }
}

//////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.Advisor;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.ruposablePointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcher;
public class ComposablePointcutExample {
    public static void main(String[] args) {
        // create target
        SampleBean target = new SampleBean();
        
        ComposablePointcut pc = new ComposablePointcut(ClassFilter.TRUE,
                new GetterMethodMatcher());
        System.out.println("Test 1");
        SampleBean proxy = getProxy(pc, target);
        testInvoke(proxy);
        System.out.println("Test 2");
        pc.union(new SetterMethodMatcher());
        proxy = getProxy(pc, target);
        testInvoke(proxy);
        
        System.out.println("Test 3");
        pc.intersection(new GetAgeMethodMatcher());
        proxy = getProxy(pc, target);
        testInvoke(proxy);
    }
    private static SampleBean getProxy(ComposablePointcut pc, SampleBean target) {
        // create the advisor
        Advisor advisor = new DefaultPointcutAdvisor(pc,
                new SimpleBeforeAdvice());
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        return (SampleBean) pf.getProxy();
    }
    private static void testInvoke(SampleBean proxy) {
        proxy.getAge();
        proxy.getName();
        proxy.setName("Rob Harrop");
    }
    private static class GetterMethodMatcher extends StaticMethodMatcher {
        public boolean matches(Method method, Class cls) {
            return (method.getName().startsWith("get"));
        }
    }
    private static class GetAgeMethodMatcher extends StaticMethodMatcher {
        public boolean matches(Method method, Class cls) {
            return "getAge".equals(method.getName());
        }
    }
    
    private static class SetterMethodMatcher extends StaticMethodMatcher {
        public boolean matches(Method method, Class cls) {
            return (method.getName().startsWith("set"));
        }
    }
}





Control Flow Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
public class TestBean {
    public void foo() {
        System.out.println("foo()");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class SimpleBeforeAdvice implements MethodBeforeAdvice {

    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("Before method: " + method);
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.ControlFlowPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
public class ControlFlowExample {
    public static void main(String[] args) {
        ControlFlowExample ex = new ControlFlowExample();
        ex.run();
    }
    public void run() {
        TestBean target = new TestBean();
        // create advisor
        Pointcut pc = new ControlFlowPointcut(ControlFlowExample.class, "test");
        Advisor advisor = new DefaultPointcutAdvisor(pc,
                new SimpleBeforeAdvice());
        // create proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        TestBean proxy = (TestBean) pf.getProxy();
        System.out.println("Trying normal invoke");
        proxy.foo();
        System.out.println("Trying under ControlFlowExample.test()");
        test(proxy);
    }
    private void test(TestBean bean) {
        bean.foo();
    }
}





Dynamic Pointcut Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public class SampleBean {
    public void foo(int x) {
        System.out.println("Invoked foo() with: "  +x);
    }
    
    public void bar() { 
        System.out.println("Invoked bar()");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class SimpleAdvice implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println(">> Invoking " + invocation.getMethod().getName());
        Object retVal = invocation.proceed();
        System.out.println(">> Done");
        return retVal;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.DynamicMethodMatcherPointcut;
public class SimpleDynamicPointcut extends DynamicMethodMatcherPointcut {
    public boolean matches(Method method, Class cls) {
        System.out.println("Static check for " + method.getName());
        return ("foo".equals(method.getName()));
    }
    public boolean matches(Method method, Class cls, Object[] args) {
        System.out.println("Dynamic check for " + method.getName());
        int x = ((Integer) args[0]).intValue();
        return (x != 100);
    }
    public ClassFilter getClassFilter() {
        return new ClassFilter() {
            public boolean matches(Class cls) {
                return (cls == SampleBean.class);
            }
        };
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
public class DynamicPointcutExample {
    public static void main(String[] args) {
        SampleBean target = new SampleBean();
        // create advisor
        Advisor advisor = new DefaultPointcutAdvisor(
                new SimpleDynamicPointcut(), new SimpleAdvice());
        
        // create proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        SampleBean proxy = (SampleBean)pf.getProxy();
        
        proxy.foo(1);
        proxy.foo(10);
        proxy.foo(100);
        
        proxy.bar();
        proxy.bar();
        proxy.bar();
    }
}





Hello World With Pointcut

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public interface IMessageWriter {
    public void writeMessage();
}

///////////////////////////////////////////////////////////////////////////////////////
public class MessageWriter implements IMessageWriter{
    public void writeMessage() {
        System.out.print("World");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class SimpleBeforeAdvice implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("Before method: " + method.getName());
    }
}
///////////////////////////////////////////////////////////////////////////////////////
public class ErrorBean {
    public void errorProneMethod() throws Exception {
        throw new Exception("Foo");
    }
    public void otherErrorProneMethod() throws IllegalArgumentException {
        throw new IllegalArgumentException("Bar");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
public class HelloWorldWithPointcut {
    public static void main(String[] args) {
        // get proxy
        ProxyFactory pf = new ProxyFactory();
        pf.addAdvisor(new DefaultPointcutAdvisor(new SimpleBeforeAdvice()));
        
        pf.setTarget(new MessageWriter());
        MessageWriter proxy1 = (MessageWriter)pf.getProxy();
        
        pf.setTarget(new MessageWriter());
        MessageWriter proxy2 = (MessageWriter)pf.getProxy();
        proxy2.writeMessage();
        
        pf.setTarget(new ErrorBean());
        ErrorBean proxy3 = (ErrorBean)pf.getProxy();
        proxy3.hashCode();
        
    }
}





Introduction Config Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
//File: introductions.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="bean" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target">
            <bean id="beanTarget" class="TargetBean">
                <property name="name">
                    <value>Rob Harrop</value>
                </property>
            </bean>
        </property>
        <property name="interceptorNames">
            <list>
                <value>advisor</value>
            </list>
        </property>
        <property name="proxyTargetClass">
            <value>true</value>
        </property>
    </bean>
    
    <bean id="advisor" class="IsModifiedAdvisor"/>
</beans>

///////////////////////////////////////////////////////////////////////////////////////
public interface IsModified {
    public boolean isModified();
}

///////////////////////////////////////////////////////////////////////////////////////
public class TargetBean {
    private String name;
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.support.DefaultIntroductionAdvisor;
public class IsModifiedAdvisor extends DefaultIntroductionAdvisor {
    public IsModifiedAdvisor() {
        super(new IsModifiedMixin());
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
public class IsModifiedMixin extends DelegatingIntroductionInterceptor
        implements IsModified {
    private boolean isModified = false;
    private Map methodCache = new HashMap();
    public boolean isModified() {
        return isModified;
    }
    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (!isModified) {
            if ((invocation.getMethod().getName().startsWith("set"))
                    && (invocation.getArguments().length == 1)) {
                // invoke the corresponding get method to see
                // if the value has actually changed
                Method getter = getGetter(invocation.getMethod());
                if (getter != null) {
                    // modification check is unimportant
                    // for write only methods
                    Object newVal = invocation.getArguments()[0];
                    Object oldVal = getter.invoke(invocation.getThis(), null);
                    
                    if((newVal == null) && (oldVal == null)) {
                        isModified = false;
                    } else if((newVal == null) && (oldVal != null)) {
                        isModified = true;
                    } else if((newVal != null) && (oldVal == null)) {
                        isModified = true;
                    } else {
                        isModified = (!newVal.equals(oldVal));
                    }
                }
            }
        }
        return super.invoke(invocation);
    }
    private Method getGetter(Method setter) {
        Method getter = null;
        // attempt cache retrieval.
        getter = (Method) methodCache.get(setter);
        if (getter != null) {
            return getter;
        }
        String getterName = setter.getName().replaceFirst("set", "get");
        try {
            getter = setter.getDeclaringClass().getMethod(getterName, null);
            // cache getter
            synchronized (methodCache) {
                methodCache.put(setter, getter);
            }
            return getter;
        } catch (NoSuchMethodException ex) {
            // must be write only
            return null;
        }
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class IntroductionConfigExample {
    public static void main(String[] args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext(
                "build/introductions.xml");
        TargetBean bean = (TargetBean) ctx.getBean("bean");
        IsModified mod = (IsModified) bean;
        // test interfaces
        System.out.println("Is TargetBean?: " + (bean instanceof TargetBean));
        System.out.println("Is IsModified?: " + (bean instanceof IsModified));
        // test is modified implementation
        System.out.println("Has been modified?: " + mod.isModified());
        bean.setName("Rob Harrop");
        System.out.println("Has been modified?: " + mod.isModified());
        bean.setName("Joe Schmoe");
        System.out.println("Has been modified?: " + mod.isModified());
    }
}





Name Pointcut Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public class NameBean {
    public void foo() {
        System.out.println("foo");
    }
    
    public void foo(int x) {
        System.out.println("foo " + x);
    }
    
    public void bar() {
        System.out.println("bar");
    }
    
    public void yup() {
        System.out.println("yup");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class SimpleAdvice implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println(">> Invoking " + invocation.getMethod().getName());
        Object retVal = invocation.proceed();
        System.out.println(">> Done");
        return retVal;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.NameMatchMethodPointcut;
public class NamePointcutExample {
    public static void main(String[] args) {
        NameBean target = new NameBean();
        // create advisor
        NameMatchMethodPointcut pc = new NameMatchMethodPointcut();
        pc.addMethodName("foo");
        pc.addMethodName("bar");
        Advisor advisor = new DefaultPointcutAdvisor(pc, new SimpleAdvice());
        
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        NameBean proxy = (NameBean)pf.getProxy();
        
        proxy.foo();
        proxy.foo(999);
        proxy.bar();
        proxy.yup();
    }
}
///////////////////////////////////////////////////////////////////////////////////////





Name Pointcut Using Advisor

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public class NameBean {
    public void foo() {
        System.out.println("foo");
    }
    
    public void foo(int x) {
        System.out.println("foo " + x);
    }
    
    public void bar() {
        System.out.println("bar");
    }
    
    public void yup() {
        System.out.println("yup");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class SimpleAdvice implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println(">> Invoking " + invocation.getMethod().getName());
        Object retVal = invocation.proceed();
        System.out.println(">> Done");
        return retVal;
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.NameMatchMethodPointcutAdvisor;
public class NamePointcutUsingAdvisor {
    public static void main(String[] args) {
        NameBean target = new NameBean();
        // create advisor
        NameMatchMethodPointcutAdvisor advisor = new NameMatchMethodPointcutAdvisor(
                new SimpleAdvice());
        advisor.addMethodName("foo");
        advisor.addMethodName("bar");
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        NameBean proxy = (NameBean) pf.getProxy();
        proxy.foo();
        proxy.foo(999);
        proxy.bar();
        proxy.yup();
    }
}





Profiling Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public class WorkerBean {
    public void doSomeWork(int noOfTimes) {
        for(int x = 0; x < noOfTimes; x++) {
            work();
        }
    }
    
    private void work() {
        System.out.print("");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.util.StopWatch;
public class ProfilingInterceptor implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        // start the stop watch
        StopWatch sw = new StopWatch();
        sw.start(invocation.getMethod().getName());
        Object returnValue = invocation.proceed();
        sw.stop();
        dumpInfo(invocation, sw.getTotalTimeMillis());
        return returnValue;
    }
    private void dumpInfo(MethodInvocation invocation, long ms) {
        Method m = invocation.getMethod();
        Object target = invocation.getThis();
        Object[] args = invocation.getArguments();
        System.out.println("Executed method: " + m.getName());
        System.out.println("On object of type: " + target.getClass().getName());
        System.out.println("With arguments:");
        for (int x = 0; x < args.length; x++) {
            System.out.print("    > " + args[x]);
        }
        System.out.print("\n");
        System.out.println("Took: " + ms + " ms");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.framework.ProxyFactory;
public class ProfilingExample {
    public static void main(String[] args) {
        WorkerBean bean = getWorkerBean();
        bean.doSomeWork(10000000);
    }
    
    private static WorkerBean getWorkerBean() {
        WorkerBean target = new WorkerBean();
        
        ProxyFactory factory = new ProxyFactory();
        factory.setTarget(target);
        factory.addAdvice(new ProfilingInterceptor());
        
        return (WorkerBean)factory.getProxy();
    }
}

///////////////////////////////////////////////////////////////////////////////////////





Proxy Factory Bean Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
//File:pfb.xml
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
    <bean id="myBean1" class="MyBean">
        <property name="dep">
            <ref local="myDependency1"/>
        </property>
    </bean>
    
    <bean id="myBean2" class="MyBean">
        <property name="dep">
            <ref local="myDependency2"/>
        </property>
    </bean>
    
    <bean id="myDependencyTarget" class="MyDependency"/>
    
    <bean id="myDependency1" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target">
            <ref local="myDependencyTarget"/>
        </property>
        <property name="interceptorNames">
            <list>
                <value>advice</value>
            </list>
        </property>
    </bean>
    
    <bean id="myDependency2" class="org.springframework.aop.framework.ProxyFactoryBean">
        <property name="target">
            <ref local="myDependencyTarget"/>
        </property>
        <property name="interceptorNames">
            <list>
                <value>advisor</value>
            </list>
        </property>
    </bean>
    
    <bean id="advice" class="MyAdvice"/>
    
    <bean id="advisor" class="org.springframework.aop.support.DefaultPointcutAdvisor">
        <property name="advice">
            <ref local="advice"/>
        </property>
        <property name="pointcut">
            <bean class="org.springframework.aop.support.JdkRegexpMethodPointcut">
                <property name="pattern">
                    <value>.*foo.*</value>
                </property>
            </bean>
        </property>
    </bean>
</beans>

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class MyAdvice implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("Executing: " + method);
    }
}
///////////////////////////////////////////////////////////////////////////////////////
public class MyBean {
    private MyDependency dep;
    
    public void execute() {
        dep.foo();
        dep.bar();
    }
    
    public void setDep(MyDependency dep) {
        this.dep = dep;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
public class MyDependency {
    public void foo() {
        System.out.println("foo()");
    }
    
    public void bar() {
        System.out.println("bar()");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
public class ProxyFactoryBeanExample {
    public static void main(String[] args) {
        ApplicationContext ctx = new FileSystemXmlApplicationContext(
                "build/pfb.xml");
        
        MyBean bean1 = (MyBean)ctx.getBean("myBean1");
        MyBean bean2 = (MyBean)ctx.getBean("myBean2");
        
        System.out.println("Bean 1");
        bean1.execute();
        
        System.out.println("\nBean 2");
        bean2.execute();
    }
}





Proxy Perf Test

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public interface ISimpleBean {
    public void advised();
    public void unadvised();
    
}

///////////////////////////////////////////////////////////////////////////////////////
public class SimpleBean implements ISimpleBean {
    private long dummy = 0;
    
    public void advised() {
        dummy = System.currentTimeMillis();
    }
    public void unadvised() {
        dummy = System.currentTimeMillis();
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class NoOpBeforeAdvice implements MethodBeforeAdvice {
    public void before(Method method, Object[] args, Object target) throws Throwable {
        // no-op
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
public class TestPointcut extends StaticMethodMatcherPointcut {
    public boolean matches(Method method, Class cls) {
        return ("advised".equals(method.getName()));
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
public class ProxyPerfTest {
    public static void main(String[] args) {
        ISimpleBean target = new SimpleBean();
        Advisor advisor = new DefaultPointcutAdvisor(new TestPointcut(),
                new NoOpBeforeAdvice());
        runCglibTests(advisor, target);
        runCglibFrozenTests(advisor, target);
        runJdkTests(advisor, target);
    }
    private static void runCglibTests(Advisor advisor, ISimpleBean target) {
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
             
        ISimpleBean proxy = (ISimpleBean)pf.getProxy();
        System.out.println("Running CGLIB (Standard) Tests");
        test(proxy);
    }
    
    private static void runCglibFrozenTests(Advisor advisor, ISimpleBean target) {
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        pf.setFrozen(true);
        
        ISimpleBean proxy = (ISimpleBean)pf.getProxy();
        System.out.println("Running CGLIB (Frozen) Tests");
        test(proxy);
    }
    
    private static void runJdkTests(Advisor advisor, ISimpleBean target) {
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        pf.setInterfaces(new Class[]{ISimpleBean.class});
        
        ISimpleBean proxy = (ISimpleBean)pf.getProxy();
        System.out.println("Running JDK Tests");
        test(proxy);
    }
    
    private static void test(ISimpleBean bean) {
        long before = 0;
        long after = 0;
        
        // test advised method
        System.out.println("Testing Advised Method");
        before = System.currentTimeMillis();
        for(int x = 0; x < 500000; x++) {
            bean.advised();
        }
        after = System.currentTimeMillis();;
        
        System.out.println("Took " + (after - before) + " ms");
        
        // testing unadvised method
        System.out.println("Testing Unadvised Method");
        before = System.currentTimeMillis(); 
        for(int x = 0; x < 500000; x++) {
            bean.unadvised();
        }
        after = System.currentTimeMillis();;
        
        System.out.println("Took " + (after - before) + " ms");
        
        // testing equals() method
        System.out.println("Testing equals() Method");
        before = System.currentTimeMillis(); 
        for(int x = 0; x < 500000; x++) {
            bean.equals(bean);
        }
        after = System.currentTimeMillis();;
        
        System.out.println("Took " + (after - before) + " ms");
        
        // testing hashCode() method
        System.out.println("Testing hashCode() Method");
        before = System.currentTimeMillis(); 
        for(int x = 0; x < 500000; x++) {
            bean.hashCode();
        }
        after = System.currentTimeMillis();;
        
        System.out.println("Took " + (after - before) + " ms");
        
        // testing method on Advised
        Advised advised = (Advised)bean;
        
        System.out.println("Testing Advised.getProxyTargetClass() Method");
        before = System.currentTimeMillis(); 
        for(int x = 0; x < 500000; x++) {
            advised.getProxyTargetClass();
        }
        after = System.currentTimeMillis();;
        
        System.out.println("Took " + (after - before) + " ms");
        
        System.out.println(">>>\n");
    }
}





Regexp Pointcut Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public class RegexpBean {
    public void foo1() {
        System.out.println("foo1");
    }
    
    public void foo2() {
        System.out.println("foo2");
    }
    
    public void bar() {
        System.out.println("bar");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class SimpleAdvice implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println(">> Invoking " + invocation.getMethod().getName());
        Object retVal = invocation.proceed();
        System.out.println(">> Done");
        return retVal;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.Advisor;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
public class RegexpPointcutExample {
    public static void main(String[] args) {
        RegexpBean target = new RegexpBean();
        
        // create the advisor
        JdkRegexpMethodPointcut pc = new JdkRegexpMethodPointcut();
        pc.setPattern(".*foo.*");
        Advisor advisor = new DefaultPointcutAdvisor(pc, new SimpleAdvice());
        
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        RegexpBean proxy = (RegexpBean)pf.getProxy();
        
        proxy.foo1();
        proxy.foo2();
        proxy.bar();
    }
}





Security Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
class UserInfo {
    private String userName;
    private String password;
    public UserInfo(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }
    
    public String getPassword() {
        return password;
    }
    public String getUserName() {
        return userName;
    }
}
///////////////////////////////////////////////////////////////////////////////////////
public class SecureBean {
    public void writeSecureMessage() {
        System.out.println("Every time I learn something new, "
                + "it pushes some old stuff out my brain");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
public class SecurityAdvice implements MethodBeforeAdvice {
    private SecurityManager securityManager;
    public SecurityAdvice() {
        this.securityManager = new SecurityManager();
    }
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        UserInfo user = securityManager.getLoggedOnUser();
        if (user == null) {
            System.out.println("No user authenticated");
            throw new SecurityException(
                    "You must login before attempting to invoke the method: "
                            + method.getName());
        } else if ("robh".equals(user.getUserName())) {
            System.out.println("Logged in user is robh - OKAY!");
        } else {
            System.out.println("Logged in user is " + user.getUserName()
                    + " NOT GOOD :(");
            throw new SecurityException("User " + user.getUserName()
                    + " is not allowed access to method " + method.getName());
        }
    }
}
///////////////////////////////////////////////////////////////////////////////////////
public class SecurityManager {
    private static ThreadLocal threadLocal = new ThreadLocal();
    public void login(String userName, String password) {
        // assumes that all credentials
        // are valid for a login
        threadLocal.set(new UserInfo(userName, password));
    }
    public void logout() {
        threadLocal.set(null);
        int x = 0;
    }
    public UserInfo getLoggedOnUser() {
        return (UserInfo) threadLocal.get();
    }
}
///////////////////////////////////////////////////////////////////////////////////////

import org.springframework.aop.framework.ProxyFactory;
public class SecurityExample {
    public static void main(String[] args) {
        // get the security manager
        SecurityManager mgr = new SecurityManager();
        
        // get the bean
        SecureBean bean = getSecureBean();
        // try as robh
        mgr.login("robh", "pwd");
        bean.writeSecureMessage();
        mgr.logout();
        
        // try as janm
        try {
            mgr.login("janm", "pwd");
            bean.writeSecureMessage();
        } catch(SecurityException ex) {
            System.out.println("Exception Caught: " + ex.getMessage());
        } finally {
            mgr.logout();
        }
        
        // try with no credentials
        try {
            bean.writeSecureMessage();
        } catch(SecurityException ex) {
            System.out.println("Exception Caught: " + ex.getMessage());
        }
    }
    
    private static SecureBean getSecureBean() {
        // create the target
        SecureBean target = new SecureBean();
        // create the advice
        SecurityAdvice advice = new SecurityAdvice();
        
        // get the proxy
        ProxyFactory factory = new ProxyFactory();
        factory.setTarget(target);
        factory.addAdvice(advice);
        SecureBean proxy = (SecureBean)factory.getProxy();
        
        return proxy;
        
    }
}





Simple After Returning Advice

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public interface IMessageWriter {
    public void writeMessage();
}

///////////////////////////////////////////////////////////////////////////////////////
public class MessageWriter implements IMessageWriter{
    public void writeMessage() {
        System.out.print("World");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class SimpleAfterReturningAdvice implements AfterReturningAdvice {
    public static void main(String[] args) {
        MessageWriter target = new MessageWriter();
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.addAdvice(new SimpleAfterReturningAdvice());
        pf.setTarget(target);
        MessageWriter proxy = (MessageWriter) pf.getProxy();
        // write the messages
        proxy.writeMessage();
    }
    public void afterReturning(Object returnValue, Method method, Object[] args,
            Object target) throws Throwable {
        System.out.println("");
        System.out.println("After method: " + method.getName());
    }
}





Simple Before Advice

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public interface IMessageWriter {
    public void writeMessage();
}
///////////////////////////////////////////////////////////////////////////////////////
public class MessageWriter implements IMessageWriter{
    public void writeMessage() {
        System.out.print("World");
    }
}
///////////////////////////////////////////////////////////////////////////////////////

import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class SimpleBeforeAdvice implements MethodBeforeAdvice {
    public static void main(String[] args) {
        MessageWriter target = new MessageWriter();
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.addAdvice(new SimpleBeforeAdvice());
        pf.setTarget(target);
        MessageWriter proxy = (MessageWriter) pf.getProxy();
        // write the messages
        proxy.writeMessage();
    }
    public void before(Method method, Object[] args, Object target)
            throws Throwable {
        System.out.println("Before method: " + method.getName());
    }
}





Simple Throws Advice

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/
///////////////////////////////////////////////////////////////////////////////////////
public class ErrorBean {
    public void errorProneMethod() throws Exception {
        throw new Exception("Foo");
    }
    public void otherErrorProneMethod() throws IllegalArgumentException {
        throw new IllegalArgumentException("Bar");
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.aop.framework.ProxyFactory;
public class SimpleThrowsAdvice implements ThrowsAdvice {
    public static void main(String[] args) throws Exception {
        ErrorBean errorBean = new ErrorBean();
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(errorBean);
        pf.addAdvice(new SimpleThrowsAdvice());
        ErrorBean proxy = (ErrorBean) pf.getProxy();
        try {
            proxy.errorProneMethod();
        } catch (Exception ignored) {
        }
        try {
            proxy.otherErrorProneMethod();
        } catch (Exception ignored) {
        }
    }
    public void afterThrowing(Exception ex) throws Throwable {
        System.out.println("***");
        System.out.println("Generic Exception Capture");
        System.out.println("Caught: " + ex.getClass().getName());
        System.out.println("***\n");
    }
    public void afterThrowing(Method method, Object[] args, Object target,
            IllegalArgumentException ex) throws Throwable {
        System.out.println("***");
        System.out.println("IllegalArgumentException Capture");
        System.out.println("Caught: " + ex.getClass().getName());
        System.out.println("Method: " + method.getName());
        System.out.println("***\n");
    }
}





Spring Aspect Introduction Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public interface IsModified {
    public boolean isModified();
}

///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.support.DefaultIntroductionAdvisor;
public class IsModifiedAdvisor extends DefaultIntroductionAdvisor {
    public IsModifiedAdvisor() {
        super(new IsModifiedMixin());
    }
}

///////////////////////////////////////////////////////////////////////////////////////
public class TargetBean {
    private String name;
    
    public void setName(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.support.DelegatingIntroductionInterceptor;
public class IsModifiedMixin extends DelegatingIntroductionInterceptor
        implements IsModified {
    private boolean isModified = false;
    private Map methodCache = new HashMap();
    public boolean isModified() {
        return isModified;
    }
    public Object invoke(MethodInvocation invocation) throws Throwable {
        if (!isModified) {
            if ((invocation.getMethod().getName().startsWith("set"))
                    && (invocation.getArguments().length == 1)) {
                // invoke the corresponding get method to see
                // if the value has actually changed
                Method getter = getGetter(invocation.getMethod());
                if (getter != null) {
                    // modification check is unimportant
                    // for write only methods
                    Object newVal = invocation.getArguments()[0];
                    Object oldVal = getter.invoke(invocation.getThis(), null);
                    
                    if((newVal == null) && (oldVal == null)) {
                        isModified = false;
                    } else if((newVal == null) && (oldVal != null)) {
                        isModified = true;
                    } else if((newVal != null) && (oldVal == null)) {
                        isModified = true;
                    } else {
                        isModified = (!newVal.equals(oldVal));
                    }
                }
            }
        }
        return super.invoke(invocation);
    }
    private Method getGetter(Method setter) {
        Method getter = null;
        // attempt cache retrieval.
        getter = (Method) methodCache.get(setter);
        if (getter != null) {
            return getter;
        }
        String getterName = setter.getName().replaceFirst("set", "get");
        try {
            getter = setter.getDeclaringClass().getMethod(getterName, null);
            // cache getter
            synchronized (methodCache) {
                methodCache.put(setter, getter);
            }
            return getter;
        } catch (NoSuchMethodException ex) {
            // must be write only
            return null;
        }
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.springframework.aop.IntroductionAdvisor;
import org.springframework.aop.framework.ProxyFactory;
public class IntroductionExample {
    public static void main(String[] args) {
        // create the target
        TargetBean target = new TargetBean();
        target.setName("Name");
        // create the advisor
        IntroductionAdvisor advisor = new IsModifiedAdvisor();
        // create the proxy
        ProxyFactory pf = new ProxyFactory();
        pf.setTarget(target);
        pf.addAdvisor(advisor);
        pf.setOptimize(true);
        
        TargetBean proxy = (TargetBean)pf.getProxy();
        IsModified proxyInterface = (IsModified)proxy;
        
        // test interfaces
        System.out.println("Is TargetBean?: " + (proxy instanceof TargetBean));
        System.out.println("Is IsModified?: " + (proxy instanceof IsModified));
        
        // test is modified implementation
        System.out.println("Has been modified?: " + proxyInterface.isModified());
        proxy.setName("Rob Harrop");
        System.out.println("Has been modified?: " + proxyInterface.isModified());
        proxy.setName("Joe Schmoe");
        System.out.println("Has been modified?: " + proxyInterface.isModified());
     
    }
}





Static Pointcut Example

/*
Pro Spring
By Rob Harrop
Jan Machacek
ISBN: 1-59059-461-4
Publisher: Apress
*/

///////////////////////////////////////////////////////////////////////////////////////
public class BeanOne {
    public void foo() {
        System.out.println("foo");
    }
    
    public void bar() {
        System.out.println("bar");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
public class BeanTwo {
    public void foo() {
        System.out.println("foo");
    }
    
    public void bar() {
        System.out.println("bar");
    }
}

///////////////////////////////////////////////////////////////////////////////////////
import java.lang.reflect.Method;
import org.springframework.aop.ClassFilter;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
public class SimpleStaticPointcut extends StaticMethodMatcherPointcut {
    public boolean matches(Method method, Class cls) {
        return ("foo".equals(method.getName()));
    }
    public ClassFilter getClassFilter() {
        return new ClassFilter() {
            public boolean matches(Class cls) {
                return (cls == BeanOne.class);
            }
        };
    }
}
///////////////////////////////////////////////////////////////////////////////////////
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class SimpleAdvice implements MethodInterceptor {
    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println(">> Invoking " + invocation.getMethod().getName());
        Object retVal = invocation.proceed();
        System.out.println(">> Done");
        return retVal;
    }
}
///////////////////////////////////////////////////////////////////////////////////////

import org.aopalliance.aop.Advice;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.support.DefaultPointcutAdvisor;
public class StaticPointcutExample {
    public static void main(String[] args) {
        BeanOne one = new BeanOne();
        BeanTwo two = new BeanTwo();
        
        BeanOne proxyOne;
        BeanTwo proxyTwo;
        
        // create pointcut, advice and advisor
        Pointcut pc = new SimpleStaticPointcut();
        Advice advice = new SimpleAdvice();
        Advisor advisor = new DefaultPointcutAdvisor(pc, advice);
        
        // create BeanOne proxy
        ProxyFactory pf = new ProxyFactory();
        pf.addAdvisor(advisor);
        pf.setTarget(one);
        proxyOne = (BeanOne)pf.getProxy();
        
        // create BeanTwo proxy
        pf = new ProxyFactory();
        pf.addAdvisor(advisor);
        pf.setTarget(two);
        proxyTwo = (BeanTwo)pf.getProxy();
        
        proxyOne.foo();
        proxyTwo.foo();
        
        proxyOne.bar();
        proxyTwo.bar();
        
    }
}