Added Tiger tests

git-svn-id: https://src.springframework.org/svn/spring-framework/trunk@255 50f2f4bb-b051-0410-bef5-90022cba6387
This commit is contained in:
Arjen Poutsma 2008-11-03 09:56:23 +00:00
parent 816b1360a6
commit b663c6ff8b
378 changed files with 36585 additions and 356 deletions

View File

@ -0,0 +1,117 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.aop.aspectj.annotation.AspectJProxyFactory;
import org.springframework.aop.framework.Advised;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Test for correct application of the bean() PCD for @AspectJ-based aspects.
*
* @author Ramnivas Laddad
* @author Juergen Hoeller
*/
public class BeanNamePointcutAtAspectTests extends AbstractDependencyInjectionSpringContextTests {
protected ITestBean testBean1;
protected ITestBean testBean2;
protected ITestBean testBean3;
protected CounterAspect counterAspect;
public BeanNamePointcutAtAspectTests() {
setPopulateProtectedVariables(true);
}
protected String getConfigPath() {
return "bean-name-pointcut-atAspect-tests.xml";
}
protected void onSetUp() throws Exception {
counterAspect.count = 0;
super.onSetUp();
}
public void testMatchingBeanName() {
assertTrue("Expected a proxy", testBean1 instanceof Advised);
// Call two methods to test for SPR-3953-like condition
testBean1.setAge(20);
testBean1.setName("");
assertEquals(2 /*TODO: make this 3 when upgrading to AspectJ 1.6.0 and advice in CounterAspect are uncommented*/, counterAspect.count);
}
public void testNonMatchingBeanName() {
assertFalse("Didn't expect a proxy", testBean3 instanceof Advised);
testBean3.setAge(20);
assertEquals(0, counterAspect.count);
}
public void testProgrammaticProxyCreation() {
ITestBean testBean = new TestBean();
AspectJProxyFactory factory = new AspectJProxyFactory();
factory.setTarget(testBean);
CounterAspect myCounterAspect = new CounterAspect();
factory.addAspect(myCounterAspect);
ITestBean proxyTestBean = factory.getProxy();
assertTrue("Expected a proxy", proxyTestBean instanceof Advised);
proxyTestBean.setAge(20);
assertEquals("Programmatically created proxy shouldn't match bean()", 0, myCounterAspect.count);
}
@Aspect
public static class CounterAspect {
int count;
@Before("execution(* set*(..)) && bean(testBean1)")
public void increment1ForAnonymousPointcut() {
count++;
}
// @Pointcut("execution(* setAge(..)) && bean(testBean1)")
// public void testBean1SetAge() {}
//
// @Pointcut("execution(* setAge(..)) && bean(testBean2)")
// public void testBean2SetAge() {}
//
// @Before("testBean1SetAge()")
// public void increment1() {
// count++;
// }
//
// @Before("testBean2SetAge()")
// public void increment2() {
// count++;
// }
}
}

View File

@ -0,0 +1,55 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.TestBean;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests to check if the first implicit join point argument is correctly processed.
* See SPR-3723 for more details.
*
* @author Ramnivas Laddad
*/
public class ImplicitJPArgumentMatchingAtAspectJTests extends AbstractDependencyInjectionSpringContextTests {
protected TestBean testBean;
public ImplicitJPArgumentMatchingAtAspectJTests() {
setPopulateProtectedVariables(true);
}
protected String getConfigPath() {
return "implicit-jp-argument-matching-atAspectJ-tests.xml";
}
public void testAspect() {
// nothing to really test; it is enough if we don't get error while creating app context
testBean.setCountry("US");
}
@Aspect
public static class CounterAtAspectJAspect {
@Around(value="execution(* org.springframework.beans.TestBean.*(..)) and this(bean) and args(argument)",
argNames="bean,argument")
public void increment(ProceedingJoinPoint pjp, TestBean bean, Object argument) throws Throwable {
pjp.proceed();
}
}
}

View File

@ -0,0 +1,53 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* @author Ramnivas Laddad
*/
public class JoinPointMonitorAspect {
/**
* The counter property is purposefully not used in the aspect to avoid distraction
* from the main bug -- merely needing a dependency on an advised bean
* is sufficient to reproduce the bug.
*/
private ICounter counter;
int beforeExecutions;
int aroundExecutions;
public void before() {
beforeExecutions++;
}
public Object around(ProceedingJoinPoint pjp) throws Throwable {
aroundExecutions++;
return pjp.proceed();
}
public ICounter getCounter() {
return counter;
}
public void setCounter(ICounter counter) {
this.counter = counter;
}
}

View File

@ -0,0 +1,58 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
/**
* @author Ramnivas Laddad
* @since 2.0
*/
@Aspect
public class JoinPointMonitorAtAspectJAspect {
/* The counter property is purposefully not used in the aspect to avoid distraction
* from the main bug -- merely needing a dependency on an advised bean
* is sufficient to reproduce the bug.
*/
private ICounter counter;
int beforeExecutions;
int aroundExecutions;
@Before("execution(* increment*())")
public void before() {
beforeExecutions++;
}
@Around("execution(* increment*())")
public Object around(ProceedingJoinPoint pjp) throws Throwable {
aroundExecutions++;
return pjp.proceed();
}
public ICounter getCounter() {
return counter;
}
public void setCounter(ICounter counter) {
this.counter = counter;
}
}

View File

@ -0,0 +1,72 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import junit.framework.TestCase;
import org.springframework.aop.framework.Advised;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Check that an aspect that depends on another bean, where the referenced bean
* itself is advised by the same aspect, works correctly.
*
* @author Ramnivas Laddad
* @author Juergen Hoeller
*/
public class PropertyDependentAspectTests extends TestCase {
public void testPropertyDependentAspectWithPropertyDeclaredBeforeAdvice() throws Exception {
checkXmlAspect("org/springframework/aop/aspectj/property-dependent-aspect-property-before-aspect-test.xml");
}
public void testPropertyDependentAspectWithPropertyDeclaredAfterAdvice() throws Exception {
checkXmlAspect("org/springframework/aop/aspectj/property-dependent-aspect-property-after-aspect-test.xml");
}
public void testPropertyDependentAtAspectJAspectWithPropertyDeclaredBeforeAdvice() throws Exception {
checkAtAspectJAspect("org/springframework/aop/aspectj/property-dependent-atAspectJ-aspect-property-before-aspect-test.xml");
}
public void testPropertyDependentAtAspectJAspectWithPropertyDeclaredAfterAdvice() throws Exception {
checkAtAspectJAspect("org/springframework/aop/aspectj/property-dependent-atAspectJ-aspect-property-after-aspect-test.xml");
}
private void checkXmlAspect(String appContextFile) {
ApplicationContext context = new ClassPathXmlApplicationContext(appContextFile);
ICounter counter = (ICounter) context.getBean("counter");
assertTrue("Proxy didn't get created", counter instanceof Advised);
counter.increment();
JoinPointMonitorAspect callCountingAspect = (JoinPointMonitorAspect)context.getBean("monitoringAspect");
assertEquals("Advise didn't get executed", 1, callCountingAspect.beforeExecutions);
assertEquals("Advise didn't get executed", 1, callCountingAspect.aroundExecutions);
}
private void checkAtAspectJAspect(String appContextFile) {
ApplicationContext context = new ClassPathXmlApplicationContext(appContextFile);
ICounter counter = (ICounter) context.getBean("counter");
assertTrue("Proxy didn't get created", counter instanceof Advised);
counter.increment();
JoinPointMonitorAtAspectJAspect callCountingAspect = (JoinPointMonitorAtAspectJAspect)context.getBean("monitoringAspect");
assertEquals("Advise didn't get executed", 1, callCountingAspect.beforeExecutions);
assertEquals("Advise didn't get executed", 1, callCountingAspect.aroundExecutions);
}
}

View File

@ -0,0 +1,195 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author Ramnivas Laddad
*/
public class ThisAndTargetSelectionOnlyPointcutsAtAspectJTests extends AbstractDependencyInjectionSpringContextTests {
protected TestInterface testBean;
protected TestInterface testAnnotatedClassBean;
protected TestInterface testAnnotatedMethodBean;
protected Counter counter;
public ThisAndTargetSelectionOnlyPointcutsAtAspectJTests() {
setPopulateProtectedVariables(true);
}
@Override
protected void onSetUp() throws Exception {
super.onSetUp();
counter.reset();
}
protected String getConfigPath() {
return "this-and-target-selectionOnly-pointcuts-atAspectJ-tests.xml";
}
public void testThisAsClassDoesNotMatch() {
testBean.doIt();
assertEquals(0, counter.thisAsClassCounter);
}
public void testThisAsInterfaceMatch() {
testBean.doIt();
assertEquals(1, counter.thisAsInterfaceCounter);
}
public void testTargetAsClassDoesMatch() {
testBean.doIt();
assertEquals(1, counter.targetAsClassCounter);
}
public void testTargetAsInterfaceMatch() {
testBean.doIt();
assertEquals(1, counter.targetAsInterfaceCounter);
}
public void testThisAsClassAndTargetAsClassCounterNotMatch() {
testBean.doIt();
assertEquals(0, counter.thisAsClassAndTargetAsClassCounter);
}
public void testThisAsInterfaceAndTargetAsInterfaceCounterMatch() {
testBean.doIt();
assertEquals(1, counter.thisAsInterfaceAndTargetAsInterfaceCounter);
}
public void testThisAsInterfaceAndTargetAsClassCounterMatch() {
testBean.doIt();
assertEquals(1, counter.thisAsInterfaceAndTargetAsInterfaceCounter);
}
public void testAtTargetClassAnnotationMatch() {
testAnnotatedClassBean.doIt();
assertEquals(1, counter.atTargetClassAnnotationCounter);
}
public void testAtAnnotationMethodAnnotationMatch() {
testAnnotatedMethodBean.doIt();
assertEquals(1, counter.atAnnotationMethodAnnotationCounter);
}
public static interface TestInterface {
public void doIt();
}
public static class TestImpl implements TestInterface {
public void doIt() {
}
}
@Retention(RetentionPolicy.RUNTIME)
public static @interface TestAnnotation {
}
@TestAnnotation
public static class AnnotatedClassTestImpl implements TestInterface {
public void doIt() {
}
}
public static class AnnotatedMethodTestImpl implements TestInterface {
@TestAnnotation
public void doIt() {
}
}
@Aspect
public static class Counter {
int thisAsClassCounter;
int thisAsInterfaceCounter;
int targetAsClassCounter;
int targetAsInterfaceCounter;
int thisAsClassAndTargetAsClassCounter;
int thisAsInterfaceAndTargetAsInterfaceCounter;
int thisAsInterfaceAndTargetAsClassCounter;
int atTargetClassAnnotationCounter;
int atAnnotationMethodAnnotationCounter;
public void reset() {
thisAsClassCounter = 0;
thisAsInterfaceCounter = 0;
targetAsClassCounter = 0;
targetAsInterfaceCounter = 0;
thisAsClassAndTargetAsClassCounter = 0;
thisAsInterfaceAndTargetAsInterfaceCounter = 0;
thisAsInterfaceAndTargetAsClassCounter = 0;
atTargetClassAnnotationCounter = 0;
atAnnotationMethodAnnotationCounter = 0;
}
@Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)")
public void incrementThisAsClassCounter() {
thisAsClassCounter++;
}
@Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface)")
public void incrementThisAsInterfaceCounter() {
thisAsInterfaceCounter++;
}
@Before("target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)")
public void incrementTargetAsClassCounter() {
targetAsClassCounter++;
}
@Before("target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface)")
public void incrementTargetAsInterfaceCounter() {
targetAsInterfaceCounter++;
}
@Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl) " +
"&& target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)")
public void incrementThisAsClassAndTargetAsClassCounter() {
thisAsClassAndTargetAsClassCounter++;
}
@Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface) " +
"&& target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface)")
public void incrementThisAsInterfaceAndTargetAsInterfaceCounter() {
thisAsInterfaceAndTargetAsInterfaceCounter++;
}
@Before("this(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestInterface) " +
"&& target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestImpl)")
public void incrementThisAsInterfaceAndTargetAsClassCounter() {
thisAsInterfaceAndTargetAsClassCounter++;
}
@Before("@target(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestAnnotation)")
public void incrementAtTargetClassAnnotationCounter() {
atTargetClassAnnotationCounter++;
}
@Before("@annotation(org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests.TestAnnotation)")
public void incrementAtAnnotationMethodAnnotationCounter() {
atAnnotationMethodAnnotationCounter++;
}
}
}

View File

@ -0,0 +1,78 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer.AmbiguousBindingException;
/**
* Tests just the annotation binding part of AspectJAdviceParameterNameDiscoverer;
* see supertype for remaining tests.
*
* @author Adrian Colyer
*/
public class TigerAspectJAdviceParameterNameDiscovererTests extends AspectJAdviceParameterNameDiscovererTests {
public void testAtThis() {
assertParameterNames(getMethod("oneAnnotation"),"@this(a)",new String[]{"a"});
}
public void testAtTarget() {
assertParameterNames(getMethod("oneAnnotation"),"@target(a)",new String[]{"a"});
}
public void testAtArgs() {
assertParameterNames(getMethod("oneAnnotation"),"@args(a)",new String[]{"a"});
}
public void testAtWithin() {
assertParameterNames(getMethod("oneAnnotation"),"@within(a)",new String[]{"a"});
}
public void testAtWithincode() {
assertParameterNames(getMethod("oneAnnotation"),"@withincode(a)",new String[]{"a"});
}
public void testAtAnnotation() {
assertParameterNames(getMethod("oneAnnotation"),"@annotation(a)",new String[]{"a"});
}
public void testAmbiguousAnnotationTwoVars() {
assertException(getMethod("twoAnnotations"),"@annotation(a) && @this(x)",AmbiguousBindingException.class,
"Found 2 potential annotation variable(s), and 2 potential argument slots");
}
public void testAmbiguousAnnotationOneVar() {
assertException(getMethod("oneAnnotation"),"@annotation(a) && @this(x)",IllegalArgumentException.class,
"Found 2 candidate annotation binding variables but only one potential argument binding slot");
}
public void testAnnotationMedley() {
assertParameterNames(getMethod("annotationMedley"),"@annotation(a) && args(count) && this(foo)",null,"ex",
new String[] {"ex","foo","count","a"});
}
public void oneAnnotation(MyAnnotation ann) {}
public void twoAnnotations(MyAnnotation ann, MyAnnotation anotherAnn) {}
public void annotationMedley(Throwable t, Object foo, int x, MyAnnotation ma) {}
@interface MyAnnotation {}
}

View File

@ -0,0 +1,261 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSourceTests;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSourceTests.TestBean3;
import org.springframework.transaction.annotation.AnnotationTransactionAttributeSourceTests.TestBean4;
import org.springframework.transaction.annotation.Transactional;
/**
* Java5-specific AspectJExpressionPointcutTests.
*
* @author Rod Johnson
*/
public class TigerAspectJExpressionPointcutTests extends TestCase {
// TODO factor into static in AspectJExpressionPointcut
private Method getAge;
private Map<String,Method> methodsOnHasGeneric = new HashMap<String,Method>();
public void setUp() throws NoSuchMethodException {
getAge = TestBean.class.getMethod("getAge", (Class[]) null);
// Assumes no overloading
for (Method m : HasGeneric.class.getMethods()) {
methodsOnHasGeneric.put(m.getName(), m);
}
}
public static class HasGeneric {
public void setFriends(List<TestBean> friends) {
}
public void setEnemies(List<TestBean> enemies) {
}
public void setPartners(List partners) {
}
public void setPhoneNumbers(List<String> numbers) {
}
}
public void testMatchGenericArgument() {
String expression = "execution(* set*(java.util.List<org.springframework.beans.TestBean>) )";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
// TODO this will currently map, would be nice for optimization
//assertTrue(ajexp.matches(HasGeneric.class));
//assertFalse(ajexp.matches(TestBean.class));
Method takesGenericList = methodsOnHasGeneric.get("setFriends");
assertTrue(ajexp.matches(takesGenericList, HasGeneric.class));
assertTrue(ajexp.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class));
assertFalse(ajexp.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class));
assertFalse(ajexp.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class));
assertFalse(ajexp.matches(getAge, TestBean.class));
}
public void testMatchVarargs() throws SecurityException, NoSuchMethodException {
String expression = "execution(int *.*(String, Object...) )";
AspectJExpressionPointcut jdbcVarArgs = new AspectJExpressionPointcut();
jdbcVarArgs.setExpression(expression);
assertFalse(jdbcVarArgs.matches(
JdbcTemplate.class.getMethod("queryForInt", String.class, Object[].class),
JdbcTemplate.class));
assertTrue(jdbcVarArgs.matches(
SimpleJdbcTemplate.class.getMethod("queryForInt", String.class, Object[].class),
SimpleJdbcTemplate.class));
Method takesGenericList = methodsOnHasGeneric.get("setFriends");
assertFalse(jdbcVarArgs.matches(takesGenericList, HasGeneric.class));
assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setEnemies"), HasGeneric.class));
assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPartners"), HasGeneric.class));
assertFalse(jdbcVarArgs.matches(methodsOnHasGeneric.get("setPhoneNumbers"), HasGeneric.class));
assertFalse(jdbcVarArgs.matches(getAge, TestBean.class));
}
public void testMatchAnnotationOnClassWithAtWithin() throws SecurityException, NoSuchMethodException {
String expression = "@within(org.springframework.transaction.annotation.Transactional)";
testMatchAnnotationOnClass(expression);
}
public void testMatchAnnotationOnClassWithoutBinding() throws SecurityException, NoSuchMethodException {
String expression = "within(@org.springframework.transaction.annotation.Transactional *)";
testMatchAnnotationOnClass(expression);
}
public void testMatchAnnotationOnClassWithSubpackageWildcard() throws SecurityException, NoSuchMethodException {
String expression = "within(@(org.springframework..*) *)";
AspectJExpressionPointcut springAnnotatedPc = testMatchAnnotationOnClass(expression);
assertFalse(springAnnotatedPc.matches(TestBean.class.getMethod("setName", String.class),
TestBean.class));
assertTrue(springAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo", (Class[]) null),
SpringAnnotated.class));
expression = "within(@(org.springframework.transaction..*) *)";
AspectJExpressionPointcut springTxAnnotatedPc = testMatchAnnotationOnClass(expression);
assertFalse(springTxAnnotatedPc.matches(SpringAnnotated.class.getMethod("foo", (Class[]) null),
SpringAnnotated.class));
}
public void testMatchAnnotationOnClassWithExactPackageWildcard() throws SecurityException, NoSuchMethodException {
String expression = "within(@(org.springframework.transaction.annotation.*) *)";
testMatchAnnotationOnClass(expression);
}
private AspectJExpressionPointcut testMatchAnnotationOnClass(String expression) throws SecurityException, NoSuchMethodException {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
assertFalse(ajexp.matches(getAge, TestBean.class));
assertTrue(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo", (Class[]) null), HasTransactionalAnnotation.class));
assertTrue(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertTrue(ajexp.matches(AnnotationTransactionAttributeSourceTests.TestBean4.class.getMethod("setName", String.class), TestBean4.class));
assertFalse(ajexp.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
return ajexp;
}
public void testAnnotationOnMethodWithFQN() throws SecurityException, NoSuchMethodException {
String expression = "@annotation(org.springframework.transaction.annotation.Transactional)";
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(expression);
assertFalse(ajexp.matches(getAge, TestBean.class));
assertFalse(ajexp.matches(HasTransactionalAnnotation.class.getMethod("foo", (Class[]) null), HasTransactionalAnnotation.class));
assertFalse(ajexp.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(ajexp.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
assertTrue(ajexp.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("getAge", (Class[]) null), TestBean3.class));
assertFalse(ajexp.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
}
public void testAnnotationOnMethodWithWildcard() throws SecurityException, NoSuchMethodException {
String expression = "execution(@(org.springframework..*) * *(..))";
AspectJExpressionPointcut anySpringMethodAnnotation = new AspectJExpressionPointcut();
anySpringMethodAnnotation.setExpression(expression);
assertFalse(anySpringMethodAnnotation.matches(getAge, TestBean.class));
assertFalse(anySpringMethodAnnotation.matches(HasTransactionalAnnotation.class.getMethod("foo", (Class[]) null), HasTransactionalAnnotation.class));
assertFalse(anySpringMethodAnnotation.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(anySpringMethodAnnotation.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
assertTrue(anySpringMethodAnnotation.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("getAge", (Class[]) null), TestBean3.class));
assertFalse(anySpringMethodAnnotation.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
}
public void testAnnotationOnMethodArgumentsWithFQN() throws SecurityException, NoSuchMethodException {
String expression = "@args(*, org.springframework.aop.aspectj.TigerAspectJExpressionPointcutTests.EmptySpringAnnotation))";
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression);
assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("foo", (Class[]) null), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
assertFalse(takesSpringAnnotatedArgument2.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("getAge", (Class[]) null), TestBean3.class));
assertFalse(takesSpringAnnotatedArgument2.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
assertTrue(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class),
ProcessesSpringAnnotatedParameters.class));
// True because it maybeMatches with potential argument subtypes
assertTrue(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, TestBean3.class),
ProcessesSpringAnnotatedParameters.class));
assertFalse(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, TestBean3.class),
ProcessesSpringAnnotatedParameters.class,
new Object[] { new TestBean(), new TestBean3()})
);
}
public void testAnnotationOnMethodArgumentsWithWildcards() throws SecurityException, NoSuchMethodException {
String expression = "execution(* *(*, @(org.springframework..*) *))";
AspectJExpressionPointcut takesSpringAnnotatedArgument2 = new AspectJExpressionPointcut();
takesSpringAnnotatedArgument2.setExpression(expression);
assertFalse(takesSpringAnnotatedArgument2.matches(getAge, TestBean.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("foo", (Class[]) null), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(HasTransactionalAnnotation.class.getMethod("bar", String.class), HasTransactionalAnnotation.class));
assertFalse(takesSpringAnnotatedArgument2.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
assertFalse(takesSpringAnnotatedArgument2.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("getAge", (Class[]) null), TestBean3.class));
assertFalse(takesSpringAnnotatedArgument2.matches(AnnotationTransactionAttributeSourceTests.TestBean3.class.getMethod("setName", String.class), TestBean3.class));
assertTrue(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesAnnotatedParameters", TestBean.class, SpringAnnotated.class),
ProcessesSpringAnnotatedParameters.class));
assertFalse(takesSpringAnnotatedArgument2.matches(
ProcessesSpringAnnotatedParameters.class.getMethod("takesNoAnnotatedParameters", TestBean.class, TestBean3.class),
ProcessesSpringAnnotatedParameters.class));
}
public static class ProcessesSpringAnnotatedParameters {
public void takesAnnotatedParameters(TestBean tb, SpringAnnotated sa) {
}
public void takesNoAnnotatedParameters(TestBean tb, TestBean3 tb3) {
}
}
@Transactional
public static class HasTransactionalAnnotation {
public void foo() {
}
public Object bar(String foo) {
throw new UnsupportedOperationException();
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface EmptySpringAnnotation {
}
@EmptySpringAnnotation
public static class SpringAnnotated {
public void foo() {
}
}
}

View File

@ -0,0 +1,903 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import java.lang.reflect.UndeclaredThrowableException;
import java.rmi.RemoteException;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.servlet.ServletException;
import junit.framework.TestCase;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclarePrecedence;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.annotation.ReflectiveAspectJAdvisorFactory.SyntheticInstantiationAdvisor;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.aop.framework.Lockable;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.interceptor.ExposeInvocationInterceptor;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.core.OrderComparator;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
/**
* Abstract tests for AspectJAdvisorFactory.
* See subclasses for tests of concrete factories.
*
* @author Rod Johnson
*/
public abstract class AbstractAspectJAdvisorFactoryTests extends TestCase {
/**
* To be overridden by concrete test subclasses.
* @return the fixture
*/
protected abstract AspectJAdvisorFactory getFixture();
public void testRejectsPerCflowAspect() {
try {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerCflowAspect(),"someBean"));
fail("Cannot accept cflow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().indexOf("PERCFLOW") != -1);
}
}
public void testRejectsPerCflowBelowAspect() {
try {
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerCflowBelowAspect(),"someBean"));
fail("Cannot accept cflowbelow");
}
catch (AopConfigException ex) {
assertTrue(ex.getMessage().indexOf("PERCFLOWBELOW") != -1);
}
}
public void testPerTargetAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerTargetAspect(), "someBean")),
TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
Advised advised = (Advised) itb;
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[3];
LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertFalse(maaif.isMaterialized());
// Check that the perclause pointcut is valid
assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertTrue(maaif.isMaterialized());
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
public void testMultiplePerTargetAspects() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
List<Advisor> advisors = new LinkedList<Advisor>();
PerTargetAspect aspect1 = new PerTargetAspect();
aspect1.count = 100;
aspect1.setOrder(10);
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1")));
PerTargetAspect aspect2 = new PerTargetAspect();
aspect2.setOrder(5);
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2")));
Collections.sort(advisors, new OrderComparator());
TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
public void testMultiplePerTargetAspectsWithOrderAnnotation() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
List<Advisor> advisors = new LinkedList<Advisor>();
PerTargetAspectWithOrderAnnotation10 aspect1 = new PerTargetAspectWithOrderAnnotation10();
aspect1.count = 100;
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect1, "someBean1")));
PerTargetAspectWithOrderAnnotation5 aspect2 = new PerTargetAspectWithOrderAnnotation5();
advisors.addAll(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspect2, "someBean2")));
Collections.sort(advisors, new OrderComparator());
TestBean itb = (TestBean) createProxy(target, advisors, TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
public void testPerThisAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new PerThisAspect(), "someBean")),
TestBean.class);
assertEquals("Around advice must NOT apply", realAge, itb.getAge());
Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length);
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertFalse(maaif.isMaterialized());
// Check that the perclause pointcut is valid
assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertTrue(maaif.isMaterialized());
assertTrue(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null));
assertEquals("Around advice must apply", 0, itb.getAge());
assertEquals("Around advice must apply", 1, itb.getAge());
}
public void testPerTypeWithinAspect() throws SecurityException, NoSuchMethodException {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
PerTypeWithinAspectInstanceFactory aif = new PerTypeWithinAspectInstanceFactory();
TestBean itb = (TestBean) createProxy(target,
getFixture().getAdvisors(aif),
TestBean.class);
assertEquals("No method calls", 0, aif.getInstantiationCount());
assertEquals("Around advice must now apply", 0, itb.getAge());
Advised advised = (Advised) itb;
// Will be ExposeInvocationInterceptor, synthetic instantiation advisor, 2 method advisors
assertEquals(4, advised.getAdvisors().length);
SyntheticInstantiationAdvisor sia = (SyntheticInstantiationAdvisor) advised.getAdvisors()[1];
assertTrue(sia.getPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
InstantiationModelAwarePointcutAdvisorImpl imapa = (InstantiationModelAwarePointcutAdvisorImpl) advised.getAdvisors()[2];
LazySingletonAspectInstanceFactoryDecorator maaif =
(LazySingletonAspectInstanceFactoryDecorator) imapa.getAspectInstanceFactory();
assertTrue(maaif.isMaterialized());
// Check that the perclause pointcut is valid
assertTrue(maaif.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
assertNotSame(imapa.getDeclaredPointcut(), imapa.getPointcut());
// Hit the method in the per clause to instantiate the aspect
itb.getSpouse();
assertTrue(maaif.isMaterialized());
assertTrue(imapa.getDeclaredPointcut().getMethodMatcher().matches(TestBean.class.getMethod("getAge"), null));
assertEquals("Around advice must still apply", 1, itb.getAge());
assertEquals("Around advice must still apply", 2, itb.getAge());
TestBean itb2 = (TestBean) createProxy(target,
getFixture().getAdvisors(aif),
TestBean.class);
assertEquals(1, aif.getInstantiationCount());
assertEquals("Around advice be independent for second instance", 0, itb2.getAge());
assertEquals(2, aif.getInstantiationCount());
}
public void testNamedPointcutAspectWithFQN() {
testNamedPointcuts(new NamedPointcutAspectWithFQN());
}
public void testNamedPointcutAspectWithoutFQN() {
testNamedPointcuts(new NamedPointcutAspectWithoutFQN());
}
public void testNamedPointcutFromAspectLibrary() {
testNamedPointcuts(new NamedPointcutAspectFromLibrary());
}
public void testNamedPointcutFromAspectLibraryWithBinding() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new NamedPointcutAspectFromLibraryWithBinding(),"someBean")),
ITestBean.class);
itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge());
assertEquals(20,target.getAge());
}
private void testNamedPointcuts(Object aspectInstance) {
TestBean target = new TestBean();
int realAge = 65;
target.setAge(realAge);
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(aspectInstance,"someBean")),
ITestBean.class);
assertEquals("Around advice must apply", -1, itb.getAge());
assertEquals(realAge, target.getAge());
}
public void testBindingWithSingleArg() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new BindingAspectWithSingleArg(),"someBean")),
ITestBean.class);
itb.setAge(10);
assertEquals("Around advice must apply", 20, itb.getAge());
assertEquals(20,target.getAge());
}
public void testBindingWithMultipleArgsDifferentlyOrdered() {
ManyValuedArgs target = new ManyValuedArgs();
ManyValuedArgs mva = (ManyValuedArgs) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ManyValuedArgs(),"someBean")),
ManyValuedArgs.class);
String a = "a";
int b = 12;
int c = 25;
String d = "d";
StringBuffer e = new StringBuffer("stringbuf");
String expectedResult = a + b+ c + d + e;
assertEquals(expectedResult, mva.mungeArgs(a, b, c, d, e));
}
/**
* In this case the introduction will be made.
*/
public void testIntroductionOnTargetNotImplementingInterface() {
NotLockable notLockableTarget = new NotLockable();
assertFalse(notLockableTarget instanceof Lockable);
NotLockable notLockable1 = (NotLockable) createProxy(notLockableTarget,
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")),
NotLockable.class);
assertTrue(notLockable1 instanceof Lockable);
Lockable lockable = (Lockable) notLockable1;
assertFalse(lockable.locked());
lockable.lock();
assertTrue(lockable.locked());
NotLockable notLockable2Target = new NotLockable();
NotLockable notLockable2 = (NotLockable) createProxy(notLockable2Target,
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")),
NotLockable.class);
assertTrue(notLockable2 instanceof Lockable);
Lockable lockable2 = (Lockable) notLockable2;
assertFalse(lockable2.locked());
notLockable2.setIntValue(1);
lockable2.lock();
try {
notLockable2.setIntValue(32);
fail();
}
catch (IllegalStateException ex) {
}
assertTrue(lockable2.locked());
}
public void testIntroductionAdvisorExcludedFromTargetImplementingInterface() {
assertTrue(AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(
new MakeLockable(),"someBean")),
CannotBeUnlocked.class).isEmpty());
assertEquals(2, AopUtils.findAdvisorsThatCanApply(getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")), NotLockable.class).size());
}
@SuppressWarnings("unchecked")
public void testIntroductionOnTargetImplementingInterface() {
CannotBeUnlocked target = new CannotBeUnlocked();
Lockable proxy = (Lockable) createProxy(target,
// Ensure that we exclude
AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
CannotBeUnlocked.class
),
CannotBeUnlocked.class);
assertTrue(proxy instanceof Lockable);
Lockable lockable = (Lockable) proxy;
assertTrue("Already locked", lockable.locked());
lockable.lock();
assertTrue("Real target ignores locking", lockable.locked());
try {
lockable.unlock();
fail();
}
catch (UnsupportedOperationException ex) {
// Ok
}
}
@SuppressWarnings("unchecked")
public void testIntroductionOnTargetExcludedByTypePattern() {
LinkedList target = new LinkedList();
List proxy = (List) createProxy(target,
AopUtils.findAdvisorsThatCanApply(
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(), "someBean")),
List.class
),
CannotBeUnlocked.class);
assertFalse("Type pattern must have excluded mixin", proxy instanceof Lockable);
}
// TODO: Why does this test fail? It hasn't been run before, so it maybe never actually passed...
public void XtestIntroductionWithArgumentBinding() {
TestBean target = new TestBean();
List<Advisor> advisors = getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeITestBeanModifiable(),"someBean"));
advisors.addAll(getFixture().getAdvisors(
new SingletonMetadataAwareAspectInstanceFactory(new MakeLockable(),"someBean")));
Modifiable modifiable = (Modifiable) createProxy(target,
advisors,
ITestBean.class);
assertTrue(modifiable instanceof Modifiable);
Lockable lockable = (Lockable) modifiable;
assertFalse(lockable.locked());
ITestBean itb = (ITestBean) modifiable;
assertFalse(modifiable.isModified());
int oldAge = itb.getAge();
itb.setAge(oldAge + 1);
assertTrue(modifiable.isModified());
modifiable.acceptChanges();
assertFalse(modifiable.isModified());
itb.setAge(itb.getAge());
assertFalse("Setting same value does not modify", modifiable.isModified());
itb.setName("And now for something completely different");
assertTrue(modifiable.isModified());
lockable.lock();
assertTrue(lockable.locked());
try {
itb.setName("Else");
fail("Should be locked");
}
catch (IllegalStateException ex) {
// Ok
}
lockable.unlock();
itb.setName("Tony");
}
public void testAspectMethodThrowsExceptionLegalOnSignature() {
TestBean target = new TestBean();
UnsupportedOperationException expectedException = new UnsupportedOperationException();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException),"someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UnsupportedOperationException ex) {
assertSame(expectedException, ex);
}
}
// TODO document this behaviour.
// Is it different AspectJ behaviour, at least for checked exceptions?
public void testAspectMethodThrowsExceptionIllegalOnSignature() {
TestBean target = new TestBean();
RemoteException expectedException = new RemoteException();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new ExceptionAspect(expectedException),"someBean"));
assertEquals("One advice method was found", 1, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
try {
itb.getAge();
fail();
}
catch (UndeclaredThrowableException ex) {
assertSame(expectedException, ex.getCause());
}
}
protected Object createProxy(Object target, List advisors, Class ... interfaces) {
ProxyFactory pf = new ProxyFactory(target);
if (interfaces.length > 1 || interfaces[0].isInterface()) {
pf.setInterfaces(interfaces);
}
else {
pf.setProxyTargetClass(true);
}
// Required everywhere we use AspectJ proxies
pf.addAdvice(ExposeInvocationInterceptor.INSTANCE);
for (Object a : advisors) {
pf.addAdvisor((Advisor) a);
}
pf.setExposeProxy(true);
return pf.getProxy();
}
public void testTwoAdvicesOnOneAspect() {
TestBean target = new TestBean();
TwoAdviceAspect twoAdviceAspect = new TwoAdviceAspect();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(twoAdviceAspect,"someBean"));
assertEquals("Two advice methods found", 2, advisors.size());
ITestBean itb = (ITestBean) createProxy(target,
advisors,
ITestBean.class);
itb.setName("");
assertEquals(0, itb.getAge());
int newAge = 32;
itb.setAge(newAge);
assertEquals(1, itb.getAge());
}
public void testAfterAdviceTypes() throws Exception {
Echo target = new Echo();
ExceptionHandling afterReturningAspect = new ExceptionHandling();
List<Advisor> advisors = getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(afterReturningAspect,"someBean"));
Echo echo = (Echo) createProxy(target,
advisors,
Echo.class);
assertEquals(0, afterReturningAspect.successCount);
assertEquals("", echo.echo(""));
assertEquals(1, afterReturningAspect.successCount);
assertEquals(0, afterReturningAspect.failureCount);
try {
echo.echo(new ServletException());
fail();
}
catch (ServletException ex) {
// Ok
}
catch (Exception ex) {
fail();
}
assertEquals(1, afterReturningAspect.successCount);
assertEquals(1, afterReturningAspect.failureCount);
assertEquals(afterReturningAspect.failureCount + afterReturningAspect.successCount, afterReturningAspect.afterCount);
}
public void testFailureWithoutExplicitDeclarePrecedence() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new NoDeclarePrecedenceShouldFail(), "someBean")),
ITestBean.class);
try {
itb.getAge();
fail();
}
catch (IllegalStateException ex) {
// expected
}
}
public void testDeclarePrecedenceNotSupported() {
TestBean target = new TestBean();
try {
createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(
new DeclarePrecedenceShouldSucceed(),"someBean")),
ITestBean.class);
fail();
}
catch (IllegalArgumentException ex) {
// Not supported in 2.0
}
}
/** Not supported in 2.0!
public void testExplicitDeclarePrecedencePreventsFailure() {
TestBean target = new TestBean();
ITestBean itb = (ITestBean) createProxy(target,
getFixture().getAdvisors(new SingletonMetadataAwareAspectInstanceFactory(new DeclarePrecedenceShouldSucceed(), "someBean")),
ITestBean.class);
assertEquals(666, itb.getAge());
}
*/
@Aspect("percflow(execution(* *(..)))")
public static class PerCflowAspect {
}
@Aspect("percflowbelow(execution(* *(..)))")
public static class PerCflowBelowAspect {
}
@Aspect("pertarget(execution(* *.getSpouse()))")
public static class PerTargetAspect implements Ordered {
public int count;
private int order = Ordered.LOWEST_PRECEDENCE;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
}
@Aspect("pertarget(execution(* *.getSpouse()))")
@Order(10)
public static class PerTargetAspectWithOrderAnnotation10 {
public int count;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
}
@Aspect("pertarget(execution(* *.getSpouse()))")
@Order(5)
public static class PerTargetAspectWithOrderAnnotation5 {
public int count;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
}
@Aspect("perthis(execution(* *.getSpouse()))")
public static class PerThisAspect {
public int count;
/**
* Just to check that this doesn't cause problems with introduction processing
*/
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.set*(int))")
public void countSetter() {
++count;
}
}
@Aspect("pertypewithin(org.springframework.beans.IOther+)")
public static class PerTypeWithinAspect {
public int count;
@Around("execution(int *.getAge())")
public int returnCountAsAge() {
return count++;
}
@Before("execution(void *.*(..))")
public void countAnythingVoid() {
++count;
}
}
private class PerTypeWithinAspectInstanceFactory implements MetadataAwareAspectInstanceFactory {
private int count;
public int getInstantiationCount() {
return this.count;
}
public Object getAspectInstance() {
++this.count;
return new PerTypeWithinAspect();
}
public ClassLoader getAspectClassLoader() {
return PerTypeWithinAspect.class.getClassLoader();
}
public AspectMetadata getAspectMetadata() {
return new AspectMetadata(PerTypeWithinAspect.class, "perTypeWithin");
}
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
@Aspect
public static class NamedPointcutAspectWithFQN {
@SuppressWarnings("unused")
private ITestBean fieldThatShouldBeIgnoredBySpringAtAspectJProcessing = new TestBean();
@Pointcut("execution(* getAge())")
public void getAge() {
}
@Around("org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.NamedPointcutAspectWithFQN.getAge()")
public int changeReturnValue(ProceedingJoinPoint pjp) {
return -1;
}
}
@Aspect
public static class NamedPointcutAspectWithoutFQN {
@Pointcut("execution(* getAge())")
public void getAge() {
}
@Around("getAge()")
public int changeReturnValue(ProceedingJoinPoint pjp) {
return -1;
}
}
@Aspect
public static class NamedPointcutAspectFromLibrary {
@Around("org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.propertyAccess()")
public int changeReturnType(ProceedingJoinPoint pjp) {
return -1;
}
@Around(value="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.integerArgOperation(x)", argNames="x")
public void doubleArg(ProceedingJoinPoint pjp, int x) throws Throwable {
pjp.proceed(new Object[] {x*2});
}
}
@Aspect
public static class Library {
@Pointcut("execution(!void get*())")
public void propertyAccess() {}
@Pointcut("execution(* *(..)) && args(i)")
public void integerArgOperation(int i) {}
}
@Aspect
public static class NamedPointcutAspectFromLibraryWithBinding {
@Around(value="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.Library.integerArgOperation(x)", argNames="x")
public void doubleArg(ProceedingJoinPoint pjp, int x) throws Throwable {
pjp.proceed(new Object[] {x*2});
}
}
@Aspect
public static class BindingAspectWithSingleArg {
@Pointcut(value="args(a)", argNames="a")
public void setAge(int a) {}
@Around(value="setAge(age)",argNames="age")
// @ArgNames({"age"}) // AMC needs more work here? ignoring pjp arg... ok??
// // argNames should be suported in Around as it is in Pointcut
public void changeReturnType(ProceedingJoinPoint pjp, int age) throws Throwable {
pjp.proceed(new Object[] {age*2});
}
}
@Aspect
public static class ManyValuedArgs {
public String mungeArgs(String a, int b, int c, String d, StringBuffer e) {
return a + b + c + d + e;
}
@Around(value="execution(String mungeArgs(..)) && args(a, b, c, d, e)",
argNames="b,c,d,e,a")
public String reverseAdvice(ProceedingJoinPoint pjp, int b, int c, String d, StringBuffer e, String a) throws Throwable {
assertEquals(a + b+ c+ d+ e, pjp.proceed());
return a + b + c + d + e;
}
}
@Aspect
public static class ExceptionAspect {
private final Exception ex;
public ExceptionAspect(Exception ex) {
this.ex = ex;
}
@Before("execution(* getAge())")
public void throwException() throws Exception {
throw ex;
}
}
@Aspect
public static class TwoAdviceAspect {
private int totalCalls;
@Around("execution(* getAge())")
public int returnCallCount(ProceedingJoinPoint pjp) throws Exception {
return totalCalls;
}
@Before("execution(* setAge(int)) && args(newAge)")
public void countSet(int newAge) throws Exception {
++totalCalls;
}
}
public static class Echo {
public Object echo(Object o) throws Exception {
if (o instanceof Exception) {
throw (Exception) o;
}
return o;
}
}
@Aspect
public static class ExceptionHandling {
public int successCount;
public int failureCount;
public int afterCount;
@AfterReturning("execution(* echo(*))")
public void succeeded() {
++successCount;
}
@AfterThrowing("execution(* echo(*))")
public void failed() {
++failureCount;
}
@After("execution(* echo(*))")
public void invoked() {
++afterCount;
}
}
@Aspect
public static class NoDeclarePrecedenceShouldFail {
@Pointcut("execution(int *.getAge())")
public void getAge() {
}
@Before("getAge()")
public void blowUpButDoesntMatterBecauseAroundAdviceWontLetThisBeInvoked() {
throw new IllegalStateException();
}
@Around("getAge()")
public int preventExecution(ProceedingJoinPoint pjp) {
return 666;
}
}
@Aspect
@DeclarePrecedence("org.springframework..*")
public static class DeclarePrecedenceShouldSucceed {
@Pointcut("execution(int *.getAge())")
public void getAge() {
}
@Before("getAge()")
public void blowUpButDoesntMatterBecauseAroundAdviceWontLetThisBeInvoked() {
throw new IllegalStateException();
}
@Around("getAge()")
public int preventExecution(ProceedingJoinPoint pjp) {
return 666;
}
}
}

View File

@ -0,0 +1,109 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import java.lang.reflect.Method;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.util.ObjectUtils;
/**
* Add a DeclareParents field in concrete subclasses, to identify
* the type pattern to apply the introduction to.
*
* @author Rod Johnson
* @since 2.0
*/
@Aspect
public abstract class AbstractMakeModifiable {
public interface MutableModifable extends Modifiable {
void markDirty();
}
public static class ModifiableImpl implements MutableModifable {
private boolean modified;
public void acceptChanges() {
modified = false;
}
public boolean isModified() {
return modified;
}
public void markDirty() {
this.modified = true;
}
}
@Before(value="execution(void set*(*)) && this(modifiable) && args(newValue)",
argNames="modifiable,newValue")
public void recordModificationIfSetterArgumentDiffersFromOldValue(JoinPoint jp,
MutableModifable mixin, Object newValue) {
/*
* We use the mixin to check and, if necessary, change,
* modification status. We need the JoinPoint to get the
* setter method. We use newValue for comparison.
* We try to invoke the getter if possible.
*/
if (mixin.isModified()) {
// Already changed, don't need to change again
//System.out.println("changed");
return;
}
// Find the current raw value, by invoking the corresponding setter
Method correspondingGetter = getGetterFromSetter(((MethodSignature) jp.getSignature()).getMethod());
boolean modified = true;
if (correspondingGetter != null) {
try {
Object oldValue = correspondingGetter.invoke(jp.getTarget());
//System.out.println("Old value=" + oldValue + "; new=" + newValue);
modified = !ObjectUtils.nullSafeEquals(oldValue, newValue);
}
catch (Exception ex) {
ex.printStackTrace();
// Don't sweat on exceptions; assume value was modified
}
}
else {
//System.out.println("cannot get getter for " + jp);
}
if (modified) {
mixin.markDirty();
}
}
private Method getGetterFromSetter(Method setter) {
String getterName = setter.getName().replaceFirst("set", "get");
try {
return setter.getDeclaringClass().getMethod(getterName, (Class[]) null);
}
catch (NoSuchMethodException ex) {
// must be write only
return null;
}
}
}

View File

@ -0,0 +1,88 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import java.lang.reflect.Method;
import junit.framework.TestCase;
import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscoverer;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.test.AssertThrows;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Adrian Colyer
* @author Juergen Hoeller
*/
public class ArgumentBindingTests extends TestCase {
public void testBindingInPointcutUsedByAdvice() {
TestBean tb = new TestBean();
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb);
proxyFactory.addAspect(NamedPointcutWithArgs.class);
final ITestBean proxiedTestBean = (ITestBean) proxyFactory.getProxy();
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
proxiedTestBean.setName("Supercalifragalisticexpialidocious");
}
}.runTest();
}
public void testAnnotationArgumentNameBinding() {
TransactionalBean tb = new TransactionalBean();
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(tb);
proxyFactory.addAspect(PointcutWithAnnotationArgument.class);
final ITransactionalBean proxiedTestBean = (ITransactionalBean) proxyFactory.getProxy();
new AssertThrows(IllegalStateException.class) {
public void test() throws Exception {
proxiedTestBean.doInTransaction();
}
}.runTest();
}
public void testParameterNameDiscoverWithReferencePointcut() throws Exception {
AspectJAdviceParameterNameDiscoverer discoverer =
new AspectJAdviceParameterNameDiscoverer("somepc(formal) && set(* *)");
discoverer.setRaiseExceptions(true);
Method methodUsedForParameterTypeDiscovery =
getClass().getMethod("methodWithOneParam", String.class);
String[] pnames = discoverer.getParameterNames(methodUsedForParameterTypeDiscovery);
assertEquals("one parameter name", 1, pnames.length);
assertEquals("formal", pnames[0]);
}
public void methodWithOneParam(String aParam) {
}
public interface ITransactionalBean {
@Transactional
void doInTransaction();
}
public static class TransactionalBean implements ITransactionalBean {
@Transactional
public void doInTransaction() {
}
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.aop.aspectj.AspectJAdviceParameterNameDiscovererTests;
/**
* Additional parameter name discover tests that need Java 5.
* Yes this will re-run the tests from the superclass, but that
* doesn't matter in the grand scheme of things...
*
* @author Adrian Colyer
*/
public class AspectJAdviceParameterNameDiscoverAnnotationTests extends AspectJAdviceParameterNameDiscovererTests {
@Retention(RetentionPolicy.RUNTIME)
@interface MyAnnotation {}
public void pjpAndAnAnnotation(ProceedingJoinPoint pjp, MyAnnotation ann) {}
public void testAnnotationBinding() {
assertParameterNames(getMethod("pjpAndAnAnnotation"),
"execution(* *(..)) && @annotation(ann)",
new String[] {"thisJoinPoint","ann"});
}
}

View File

@ -0,0 +1,84 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import junit.framework.TestCase;
import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.aspectj.AspectJExpressionPointcutTests;
import org.springframework.aop.framework.AopConfigException;
import org.springframework.beans.TestBean;
/**
* @author Rod Johnson
*/
public class AspectJPointcutAdvisorTests extends TestCase {
private AspectJAdvisorFactory af = new ReflectiveAspectJAdvisorFactory();
public void testSingleton() throws SecurityException, NoSuchMethodException {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(AspectJExpressionPointcutTests.MATCH_ALL_METHODS);
InstantiationModelAwarePointcutAdvisorImpl ajpa = new InstantiationModelAwarePointcutAdvisorImpl(af, ajexp,
new SingletonMetadataAwareAspectInstanceFactory(new AbstractAspectJAdvisorFactoryTests.ExceptionAspect(null),"someBean"),
TestBean.class.getMethod("getAge", (Class[]) null),1,"someBean");
assertSame(Pointcut.TRUE, ajpa.getAspectMetadata().getPerClausePointcut());
assertFalse(ajpa.isPerInstance());
}
public void testPerTarget() throws SecurityException, NoSuchMethodException {
AspectJExpressionPointcut ajexp = new AspectJExpressionPointcut();
ajexp.setExpression(AspectJExpressionPointcutTests.MATCH_ALL_METHODS);
InstantiationModelAwarePointcutAdvisorImpl ajpa = new InstantiationModelAwarePointcutAdvisorImpl(af, ajexp,
new SingletonMetadataAwareAspectInstanceFactory(new AbstractAspectJAdvisorFactoryTests.PerTargetAspect(),"someBean"), null, 1, "someBean");
assertNotSame(Pointcut.TRUE, ajpa.getAspectMetadata().getPerClausePointcut());
assertTrue(ajpa.getAspectMetadata().getPerClausePointcut() instanceof AspectJExpressionPointcut);
assertTrue(ajpa.isPerInstance());
assertTrue(ajpa.getAspectMetadata().getPerClausePointcut().getClassFilter().matches(TestBean.class));
assertFalse(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(
TestBean.class.getMethod("getAge", (Class[]) null),
TestBean.class));
assertTrue(ajpa.getAspectMetadata().getPerClausePointcut().getMethodMatcher().matches(
TestBean.class.getMethod("getSpouse", (Class[]) null),
TestBean.class));
}
public void testPerCflowTarget() {
testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowAspect.class);
}
public void testPerCflowBelowTarget() {
testIllegalInstantiationModel(AbstractAspectJAdvisorFactoryTests.PerCflowBelowAspect.class);
}
private void testIllegalInstantiationModel(Class c) {
try {
new AspectMetadata(c,"someBean");
fail();
}
catch (AopConfigException ex) {
// OK
}
}
}

View File

@ -0,0 +1,65 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import junit.framework.TestCase;
import org.aspectj.lang.reflect.PerClauseKind;
import org.springframework.aop.Pointcut;
import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.ExceptionAspect;
import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.PerTargetAspect;
import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests.PerThisAspect;
/**
*
* @since 2.0
* @author Rod Johnson
*
*/
public class AspectMetadataTests extends TestCase {
public void testNotAnAspect() {
try {
new AspectMetadata(String.class,"someBean");
fail();
}
catch (IllegalArgumentException ex) {
// Ok
}
}
public void testSingletonAspect() {
AspectMetadata am = new AspectMetadata(ExceptionAspect.class,"someBean");
assertFalse(am.isPerThisOrPerTarget());
assertSame(Pointcut.TRUE, am.getPerClausePointcut());
assertEquals(PerClauseKind.SINGLETON, am.getAjType().getPerClause().getKind());
}
public void testPerTargetAspect() {
AspectMetadata am = new AspectMetadata(PerTargetAspect.class,"someBean");
assertTrue(am.isPerThisOrPerTarget());
assertNotSame(Pointcut.TRUE, am.getPerClausePointcut());
assertEquals(PerClauseKind.PERTARGET, am.getAjType().getPerClause().getKind());
}
public void testPerThisAspect() {
AspectMetadata am = new AspectMetadata(PerThisAspect.class,"someBean");
assertTrue(am.isPerThisOrPerTarget());
assertNotSame(Pointcut.TRUE, am.getPerClausePointcut());
assertEquals(PerClauseKind.PERTHIS, am.getAjType().getPerClause().getKind());
}
}

View File

@ -0,0 +1,122 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import junit.framework.TestCase;
import org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue;
import org.springframework.aop.aspectj.autoproxy.PerThisAspect;
import org.springframework.test.AssertThrows;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class AspectProxyFactoryTests extends TestCase {
public void testWithNonAspect() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(new TestBean());
proxyFactory.addAspect(TestBean.class);
}
}.runTest();
}
public void testWithSimpleAspect() throws Exception {
TestBean bean = new TestBean();
bean.setAge(2);
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(bean);
proxyFactory.addAspect(MultiplyReturnValue.class);
ITestBean proxy = proxyFactory.getProxy();
assertEquals("Multiplication did not occur", bean.getAge() * 2, proxy.getAge());
}
public void testWithPerThisAspect() throws Exception {
TestBean bean1 = new TestBean();
TestBean bean2 = new TestBean();
AspectJProxyFactory pf1 = new AspectJProxyFactory(bean1);
pf1.addAspect(PerThisAspect.class);
AspectJProxyFactory pf2 = new AspectJProxyFactory(bean2);
pf2.addAspect(PerThisAspect.class);
ITestBean proxy1 = pf1.getProxy();
ITestBean proxy2 = pf2.getProxy();
assertEquals(0, proxy1.getAge());
assertEquals(1, proxy1.getAge());
assertEquals(0, proxy2.getAge());
assertEquals(2, proxy1.getAge());
}
public void testWithInstanceWithNonAspect() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
AspectJProxyFactory pf = new AspectJProxyFactory();
pf.addAspect(new TestBean());
}
}.runTest();
}
public void testWithInstance() throws Exception {
MultiplyReturnValue aspect = new MultiplyReturnValue();
int multiple = 3;
aspect.setMultiple(multiple);
TestBean target = new TestBean();
target.setAge(24);
AspectJProxyFactory proxyFactory = new AspectJProxyFactory(target);
proxyFactory.addAspect(aspect);
ITestBean proxy = proxyFactory.getProxy();
assertEquals(target.getAge() * multiple, proxy.getAge());
}
public void testWithNonSingletonAspectInstance() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
AspectJProxyFactory pf = new AspectJProxyFactory();
pf.addAspect(new PerThisAspect());
}
}.runTest();
}
public static interface ITestBean {
int getAge();
}
public static class TestBean implements ITestBean {
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.springframework.aop.framework.Lockable;
/**
*
*
* @author Rod Johnson
*
*/
public class CannotBeUnlocked implements Lockable, Comparable {
public void lock() {
}
public void unlock() {
throw new UnsupportedOperationException();
}
public boolean locked() {
return true;
}
public int compareTo(Object arg0) {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,28 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.annotation.Aspect;
/**
* @author Rob Harrop
* @since 2.o
*/
@Aspect
public class FooAspect {
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.DeclareParents;
/**
* Adds a declare parents pointcut.
* @author Rod Johnson
* @since 2.0
*/
@Aspect
public class MakeITestBeanModifiable extends AbstractMakeModifiable {
@DeclareParents(value = "org.springframework.beans.ITestBean+",
defaultImpl=ModifiableImpl.class)
public static MutableModifable mixin;
}

View File

@ -0,0 +1,73 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.DeclareParents;
import org.springframework.aop.framework.DefaultLockable;
import org.springframework.aop.framework.Lockable;
/**
* Demonstrates introductions, AspectJ annotation style.
* <p>
* @author Rod Johnson
* @since 2.0
*/
@Aspect
public class MakeLockable {
@DeclareParents(value = "org.springframework..*",
defaultImpl=DefaultLockable.class)
public static Lockable mixin;
@Before(value="execution(void set*(*)) && this(mixin)", argNames="mixin")
public void checkNotLocked(
Lockable mixin) // Bind to arg
{
// Can also obtain the mixin (this) this way
//Lockable mixin = (Lockable) jp.getThis();
if (mixin.locked()) {
throw new IllegalStateException();
}
}
}
/*
*
* public aspect MakeLockable {
*
* declare parents org....* implements Lockable;
*
* private boolean Lockable.locked;
* public void Lockable.lock() {
this.locked = true;
}
* public void Lockable.unlock() {
this.locked = false;
}
* public boolean Lockable.locked() {
return this.locked;
}
*
*
* }
*/

View File

@ -0,0 +1,30 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
/**
* Used as a mixin.
*
* @author Rod Johnson
*/
public interface Modifiable {
boolean isModified();
void acceptChanges();
}

View File

@ -0,0 +1,39 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* @author Adrian Colyer
*/
@Aspect
public class NamedPointcutWithArgs {
@Pointcut("execution(* *(..)) && args(s,..)")
public void pointcutWithArgs(String s) {}
@Around("pointcutWithArgs(aString)")
public Object doAround(ProceedingJoinPoint pjp, String aString) throws Throwable {
System.out.println("got '" + aString + "' at '" + pjp + "'");
throw new IllegalArgumentException(aString);
}
}

View File

@ -0,0 +1,15 @@
package org.springframework.aop.aspectj.annotation;
public class NotLockable {
private int intValue;
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Juergen Hoeller
*/
@Aspect
public class PointcutWithAnnotationArgument {
@Around(value = "execution(* org.springframework..*.*(..)) && @annotation(transaction)")
public Object around(ProceedingJoinPoint pjp, Transactional transaction) throws Throwable {
System.out.println("Invoked with transaction " + transaction);
throw new IllegalStateException();
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.annotation;
/**
* Tests for ReflectiveAtAspectJAdvisorFactory.
* Tests are inherited: we only set the test fixture here.
*
* @author Rod Johnson
* @since 2.0
*/
public class ReflectiveAspectJAdvisorFactoryTests extends AbstractAspectJAdvisorFactoryTests {
@Override
protected AspectJAdvisorFactory getFixture() {
return new ReflectiveAspectJAdvisorFactory();
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
@Aspect
public class AdviceUsingThisJoinPoint {
private String lastEntry = "";
public String getLastMethodEntered() {
return this.lastEntry;
}
@Pointcut("execution(* *(..))")
public void methodExecution() {}
@Before("methodExecution()")
public void entryTrace(JoinPoint jp) {
this.lastEntry = jp.toString();
}
}

View File

@ -0,0 +1,33 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
/**
* @author Adrian Colyer
* @since 2.0
*/
public interface AnnotatedTestBean {
String doThis();
String doThat();
String doTheOther();
String[] doArray();
}

View File

@ -0,0 +1,48 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.transaction.annotation.Transactional;
/**
* @author Adrian Colyer
* @since 2.0
*/
@Transactional
public class AnnotatedTestBeanImpl implements AnnotatedTestBean {
@TestAnnotation("this value")
public String doThis() {
return "doThis";
}
@TestAnnotation("that value")
public String doThat() {
return "doThat";
}
@TestAnnotation("array value")
public String[] doArray() {
return new String[] {"doThis", "doThat"};
}
// not annotated
public String doTheOther() {
return "doTheOther";
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
/**
* @author Adrian Colyer
*/
public class AnnotationBindingTestAspect {
public String doWithAnnotation(ProceedingJoinPoint pjp, TestAnnotation testAnnotation) throws Throwable {
return testAnnotation.value();
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author Adrian Colyer
*/
public class AnnotationBindingTests extends AbstractDependencyInjectionSpringContextTests {
private AnnotatedTestBean testBean;
@Override
protected String getConfigPath() {
return "around-advice-tests.xml";
}
public void setTestBean(AnnotatedTestBean testBean) {
this.testBean = testBean;
}
public void testAnnotationBindingInAroundAdvice() {
assertEquals("this value", testBean.doThis());
assertEquals("that value", testBean.doThat());
}
public void testNoMatchingWithoutAnnotationPresent() {
assertEquals("doTheOther", testBean.doTheOther());
}
}

View File

@ -0,0 +1,56 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author Juergen Hoeller
*/
public class AnnotationPointcutTests extends AbstractDependencyInjectionSpringContextTests {
private AnnotatedTestBean testBean;
@Override
protected String getConfigPath() {
return "annotationPointcut.xml";
}
public void setTestBean(AnnotatedTestBean testBean) {
this.testBean = testBean;
}
public void testAnnotationBindingInAroundAdvice() {
assertEquals("this value", testBean.doThis());
}
public void testNoMatchingWithoutAnnotationPresent() {
assertEquals("doTheOther", testBean.doTheOther());
}
public static class TestMethodInterceptor implements MethodInterceptor {
public Object invoke(MethodInvocation methodInvocation) throws Throwable {
return "this value";
}
}
}

View File

@ -0,0 +1,46 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.beans.ITestBean;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author Rod Johnson
* @author Rob Harrop
*/
public class AspectJAutoProxyCreatorAndLazyInitTargetSourceTests extends AbstractDependencyInjectionSpringContextTests {
public AspectJAutoProxyCreatorAndLazyInitTargetSourceTests() {
setAutowireMode(AUTOWIRE_BY_NAME);
}
@Override
protected String getConfigPath() {
return "lazy.xml";
}
public void testAdrian() {
ITestBean adrian = (ITestBean) applicationContext.getBean("adrian");
assertEquals(0, LazyTestBean.instantiations);
assertNotNull(adrian);
adrian.getAge();
assertEquals(68, adrian.getAge());
assertEquals(1, LazyTestBean.instantiations);
}
}

View File

@ -0,0 +1,319 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import junit.framework.TestCase;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests;
import org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator;
import org.springframework.aop.aspectj.annotation.AspectMetadata;
import org.springframework.aop.config.AopConfigUtils;
import org.springframework.aop.framework.ProxyConfig;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.INestedTestBean;
import org.springframework.beans.ITestBean;
import org.springframework.beans.NestedTestBean;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.util.StopWatch;
/**
* Tests for AspectJ auto-proxying. Includes mixing with Spring AOP Advisors
* to demonstrate that existing autoproxying contract is honoured.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class AspectJAutoProxyCreatorTests extends TestCase {
private static final Log factoryLog = LogFactory.getLog(DefaultListableBeanFactory.class);
public void testAspectsAreApplied() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspects.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
assertEquals(68, tb.getAge());
MethodInvokingFactoryBean factoryBean = (MethodInvokingFactoryBean) bf.getBean("&factoryBean");
assertTrue(AopUtils.isAopProxy(factoryBean.getTargetObject()));
assertEquals(68, ((ITestBean) factoryBean.getTargetObject()).getAge());
}
public void testMultipleAspectsWithParameterApplied() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspects.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
tb.setAge(10);
assertEquals(20, tb.getAge());
}
public void testAspectsAreAppliedInDefinedOrder() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsWithOrdering.xml");
ITestBean tb = (ITestBean) bf.getBean("adrian");
assertEquals(71, tb.getAge());
}
public void testAspectsAndAdvisorAreApplied() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsPlusAdvisor.xml");
ITestBean shouldBeWeaved = (ITestBean) ac.getBean("adrian");
testAspectsAndAdvisorAreApplied(ac, shouldBeWeaved);
}
public void testAspectsAndAdvisorAppliedToPrototypeIsFastEnough() {
if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) {
// Skip this test: Trace logging blows the time limit.
return;
}
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsPlusAdvisor.xml");
StopWatch sw = new StopWatch();
sw.start("prototype");
for (int i = 0; i < 10000; i++) {
ITestBean shouldBeWeaved = (ITestBean) ac.getBean("adrian2");
if (i < 10) {
testAspectsAndAdvisorAreApplied(ac, shouldBeWeaved);
}
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000);
}
public void testAspectsAndAdvisorNotAppliedToPrototypeIsFastEnough() {
if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) {
// Skip this test: Trace logging blows the time limit.
return;
}
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsPlusAdvisor.xml");
StopWatch sw = new StopWatch();
sw.start("prototype");
for (int i = 0; i < 100000; i++) {
INestedTestBean shouldNotBeWeaved = (INestedTestBean) ac.getBean("i21");
if (i < 10) {
assertFalse(AopUtils.isAopProxy(shouldNotBeWeaved));
}
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("Prototype creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 3000);
}
public void testAspectsAndAdvisorNotAppliedToManySingletonsIsFastEnough() {
if (factoryLog.isTraceEnabled() || factoryLog.isDebugEnabled()) {
// Skip this test: Trace logging blows the time limit.
return;
}
GenericApplicationContext ac = new GenericApplicationContext();
new XmlBeanDefinitionReader(ac).loadBeanDefinitions(
"/org/springframework/aop/aspectj/autoproxy/aspectsPlusAdvisor.xml");
for (int i = 0; i < 10000; i++) {
ac.registerBeanDefinition("singleton" + i, new RootBeanDefinition(NestedTestBean.class));
}
StopWatch sw = new StopWatch();
sw.start("singleton");
ac.refresh();
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("Singleton creation took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 4000);
}
public void testAspectsAndAdvisorAreAppliedEvenIfComingFromParentFactory() {
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsPlusAdvisor.xml");
GenericApplicationContext childAc = new GenericApplicationContext(ac);
// Create a child factory with a bean that should be weaved
RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
bd.getPropertyValues().addPropertyValue(new PropertyValue("name", "Adrian")).
addPropertyValue(new PropertyValue("age", new Integer(34)));
childAc.registerBeanDefinition("adrian2", bd);
// Register the advisor auto proxy creator with subclass
childAc.registerBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class.getName(),
new RootBeanDefinition(AnnotationAwareAspectJAutoProxyCreator.class));
childAc.refresh();
ITestBean beanFromChildContextThatShouldBeWeaved = (ITestBean) childAc.getBean("adrian2");
//testAspectsAndAdvisorAreApplied(childAc, (ITestBean) ac.getBean("adrian"));
testAspectsAndAdvisorAreApplied(childAc, beanFromChildContextThatShouldBeWeaved);
}
protected void testAspectsAndAdvisorAreApplied(ApplicationContext ac, ITestBean shouldBeWeaved) {
TestBeanAdvisor tba = (TestBeanAdvisor) ac.getBean("advisor");
MultiplyReturnValue mrv = (MultiplyReturnValue) ac.getBean("aspect");
assertEquals(3, mrv.getMultiple());
tba.count = 0;
mrv.invocations = 0;
assertTrue("Autoproxying must apply from @AspectJ aspect", AopUtils.isAopProxy(shouldBeWeaved));
assertEquals("Adrian", shouldBeWeaved.getName());
assertEquals(0, mrv.invocations);
assertEquals(34 * mrv.getMultiple(), shouldBeWeaved.getAge());
assertEquals("Spring advisor must be invoked", 2, tba.count);
assertEquals("Must be able to hold state in aspect", 1, mrv.invocations);
}
public void testPerThisAspect() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/perthis.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian1));
assertEquals(0, adrian1.getAge());
assertEquals(1, adrian1.getAge());
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
assertNotSame(adrian1, adrian2);
assertTrue(AopUtils.isAopProxy(adrian1));
assertEquals(0, adrian2.getAge());
assertEquals(1, adrian2.getAge());
assertEquals(2, adrian2.getAge());
assertEquals(3, adrian2.getAge());
assertEquals(2, adrian1.getAge());
}
public void testPerTargetAspect() throws SecurityException, NoSuchMethodException {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/pertarget.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian1));
// Does not trigger advice or count
int explicitlySetAge = 25;
adrian1.setAge(explicitlySetAge);
assertEquals("Setter does not initiate advice", explicitlySetAge, adrian1.getAge());
// Fire aspect
AspectMetadata am = new AspectMetadata(AbstractAspectJAdvisorFactoryTests.PerTargetAspect.class, "someBean");
assertTrue(am.getPerClausePointcut().getMethodMatcher().matches(TestBean.class.getMethod("getSpouse"), null));
adrian1.getSpouse();
assertEquals("Advice has now been instantiated", 0, adrian1.getAge());
adrian1.setAge(11);
assertEquals("Any int setter increments", 2, adrian1.getAge());
adrian1.setName("Adrian");
//assertEquals("Any other setter does not increment", 2, adrian1.getAge());
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
assertNotSame(adrian1, adrian2);
assertTrue(AopUtils.isAopProxy(adrian1));
assertEquals(34, adrian2.getAge());
adrian2.getSpouse();
assertEquals("Aspect now fired", 0, adrian2.getAge());
assertEquals(1, adrian2.getAge());
assertEquals(2, adrian2.getAge());
assertEquals(3, adrian1.getAge());
}
public void testTwoAdviceAspectSingleton() {
doTestTwoAdviceAspectWith("twoAdviceAspect.xml");
}
public void testTwoAdviceAspectPrototype() {
doTestTwoAdviceAspectWith("twoAdviceAspectPrototype.xml");
}
private void doTestTwoAdviceAspectWith(String location) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/" + location);
boolean aspectSingleton = bf.isSingleton("aspect");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
testPrototype(adrian1, 0);
ITestBean adrian2 = (ITestBean) bf.getBean("adrian");
assertNotSame(adrian1, adrian2);
testPrototype(adrian2, aspectSingleton ? 2 : 0);
}
public void testAdviceUsingJoinPoint() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/usesJoinPointAspect.xml");
ITestBean adrian1 = (ITestBean) bf.getBean("adrian");
adrian1.getAge();
AdviceUsingThisJoinPoint aspectInstance = (AdviceUsingThisJoinPoint) bf.getBean("aspect");
//(AdviceUsingThisJoinPoint) Aspects.aspectOf(AdviceUsingThisJoinPoint.class);
//assertEquals("method-execution(int TestBean.getAge())",aspectInstance.getLastMethodEntered());
assertTrue(aspectInstance.getLastMethodEntered().indexOf("TestBean.getAge())") != 0);
}
public void testIncludeMechanism() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/usesInclude.xml");
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
assertEquals(68, adrian.getAge());
}
private void testPrototype(ITestBean adrian1, int start) {
assertTrue(AopUtils.isAopProxy(adrian1));
//TwoAdviceAspect twoAdviceAspect = (TwoAdviceAspect) bf.getBean(TwoAdviceAspect.class.getName());
adrian1.setName("");
assertEquals(start++, adrian1.getAge());
int newAge = 32;
adrian1.setAge(newAge);
assertEquals(start++, adrian1.getAge());
adrian1.setAge(0);
assertEquals(start++, adrian1.getAge());
}
public void testForceProxyTargetClass() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsWithCGLIB.xml");
ProxyConfig pc = (ProxyConfig) bf.getBean(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertTrue("should be proxying classes", pc.isProxyTargetClass());
}
public void testWithAbstractFactoryBeanAreApplied() {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/aspectsWithAbstractBean.xml");
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
assertEquals(68, adrian.getAge());
}
public void testRetryAspect() throws Exception {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(
"/org/springframework/aop/aspectj/autoproxy/retryAspect.xml");
UnreliableBean bean = (UnreliableBean) bf.getBean("unreliableBean");
RetryAspect aspect = (RetryAspect) bf.getBean("retryAspect");
int attempts = bean.unreliable();
assertEquals(2, attempts);
assertEquals(2, aspect.getBeginCalls());
assertEquals(1, aspect.getRollbackCalls());
assertEquals(1, aspect.getCommitCalls());
}
}

View File

@ -0,0 +1,97 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import junit.framework.TestCase;
import org.springframework.aop.config.AopConfigUtils;
import org.springframework.aop.config.AopNamespaceUtils;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.parsing.CollectingReaderEventListener;
import org.springframework.beans.factory.parsing.PassThroughSourceExtractor;
import org.springframework.beans.factory.parsing.SourceExtractor;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ParserContext;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlReaderContext;
/**
* @author Rob Harrop
*/
public class AspectJNamespaceHandlerTests extends TestCase {
private ParserContext parserContext;
private CollectingReaderEventListener readerEventListener = new CollectingReaderEventListener();
private BeanDefinitionRegistry registry = new DefaultListableBeanFactory();
protected void setUp() throws Exception {
SourceExtractor sourceExtractor = new PassThroughSourceExtractor();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this.registry);
XmlReaderContext readerContext =
new XmlReaderContext(null, null, this.readerEventListener, sourceExtractor, reader, null);
this.parserContext = new ParserContext(readerContext, null);
}
public void testRegisterAutoProxyCreator() throws Exception {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount());
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount());
}
public void testRegisterAspectJAutoProxyCreator() throws Exception {
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount());
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect number of definitions registered", 1, registry.getBeanDefinitionCount());
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertEquals("Incorrect APC class",
AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName());
}
public void testRegisterAspectJAutoProxyCreatorWithExistingAutoProxyCreator() throws Exception {
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals(1, registry.getBeanDefinitionCount());
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect definition count", 1, registry.getBeanDefinitionCount());
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertEquals("APC class not switched",
AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName());
}
public void testRegisterAutoProxyCreatorWhenAspectJAutoProxyCreatorAlreadyExists() throws Exception {
AopNamespaceUtils.registerAspectJAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals(1, registry.getBeanDefinitionCount());
AopNamespaceUtils.registerAutoProxyCreatorIfNecessary(this.parserContext, null);
assertEquals("Incorrect definition count", 1, registry.getBeanDefinitionCount());
BeanDefinition definition = registry.getBeanDefinition(AopConfigUtils.AUTO_PROXY_CREATOR_BEAN_NAME);
assertEquals("Incorrect APC class",
AspectJAwareAdvisorAutoProxyCreator.class.getName(), definition.getBeanClassName());
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.aop.support.AopUtils;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.io.IOException;
/**
* @author Rob Harrop
* @since 2.0
*/
public class AtAspectJAfterThrowingTests extends TestCase {
public void testAccessThrowable() throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("afterThrowingAdviceTests.xml", getClass());
ITestBean bean = (ITestBean) context.getBean("testBean");
ExceptionHandlingAspect aspect = (ExceptionHandlingAspect) context.getBean("aspect");
assertTrue(AopUtils.isAopProxy(bean));
try {
bean.unreliableFileOperation();
}
catch (IOException e) {
//
}
assertEquals(1, aspect.handled);
assertNotNull(aspect.lastException);
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* @author Adrian Colyer
* @author Juergen Hoeller
*/
@Aspect
public class AtAspectJAnnotationBindingTestAspect {
@Around("execution(* *(..)) && @annotation(testAnn)")
public Object doWithAnnotation(ProceedingJoinPoint pjp, TestAnnotation testAnn)
throws Throwable {
String annValue = testAnn.value();
Object result = pjp.proceed();
return (result instanceof String ? annValue + " " + result : result);
}
}

View File

@ -0,0 +1,54 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author Adrian Colyer
* @author Juergen Hoeller
*/
public class AtAspectJAnnotationBindingTests extends AbstractDependencyInjectionSpringContextTests {
private AnnotatedTestBean testBean;
public void setTestBean(AnnotatedTestBean testBean) {
this.testBean = testBean;
}
@Override
protected String getConfigPath() {
return "ataspectj-around-advice-tests.xml";
}
public void testAnnotationBindingInAroundAdvice() {
assertEquals("this value doThis", testBean.doThis());
assertEquals("that value doThat", testBean.doThat());
assertEquals(2, testBean.doArray().length);
}
public void testNoMatchingWithoutAnnotationPresent() {
assertEquals("doTheOther", testBean.doTheOther());
}
public void testPointcutEvaulatedAgainstArray() {
applicationContext.getBean("arrayFactoryBean");
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* @author Juergen Hoeller
*/
@Aspect
public class DummyAspect {
@Around("execution(* setAge(int))")
public Object test(ProceedingJoinPoint pjp) throws Throwable {
return pjp.proceed();
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* @author Juergen Hoeller
*/
@Aspect
public class DummyAspectWithParameter {
@Around("execution(* setAge(int)) && args(age)")
public Object test(ProceedingJoinPoint pjp, int age) throws Throwable {
return pjp.proceed();
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.beans.factory.FactoryBean;
/**
* @author Rob Harrop
*/
public class DummyFactoryBean implements FactoryBean {
public Object getObject() throws Exception {
throw new UnsupportedOperationException();
}
public Class getObjectType() {
throw new UnsupportedOperationException();
}
public boolean isSingleton() {
throw new UnsupportedOperationException();
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import java.io.IOException;
/**
* @author Rob Harrop
* @since 2.0
*/
@Aspect
public class ExceptionHandlingAspect {
public int handled;
public IOException lastException;
@AfterThrowing(pointcut = "within(org.springframework.beans.ITestBean+)", throwing = "ex")
public void handleIOException(IOException ex) {
handled++;
lastException = ex;
}
}

View File

@ -0,0 +1,38 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
/**
* @author Juergen Hoeller
*/
@Aspect
@Order(10)
public class IncreaseReturnValue {
@Around("execution(int *.getAge())")
public Object doubleReturnValue(ProceedingJoinPoint pjp) throws Throwable {
int result = (Integer) pjp.proceed();
return result + 3;
}
}

View File

@ -0,0 +1,36 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.beans.TestBean;
/**
* @author Rod Johnson
* @since 2.0
*/
public class LazyTestBean extends TestBean {
public static int instantiations;
/**
*
*/
public LazyTestBean() {
++instantiations;
}
}

View File

@ -0,0 +1,48 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* @author Rod Johnson
*/
@Aspect
public class MultiplyReturnValue {
private int multiple = 2;
public int invocations;
public void setMultiple(int multiple) {
this.multiple = multiple;
}
public int getMultiple() {
return this.multiple;
}
@Around("execution(int *.getAge())")
public Object doubleReturnValue(ProceedingJoinPoint pjp) throws Throwable {
++this.invocations;
int result = (Integer) pjp.proceed();
return result * this.multiple;
}
}

View File

@ -0,0 +1,37 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
@Aspect("perthis(execution(* getAge()))")
public class PerThisAspect {
private int invocations = 0;
public int getInvocations() {
return this.invocations;
}
@Around("execution(* getAge())")
public int changeAge(ProceedingJoinPoint pjp) throws Throwable {
return invocations++;
}
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.core.io.Resource;
/**
* @author Juergen Hoeller
*/
public class ResourceArrayFactoryBean implements FactoryBean {
@TestAnnotation("some value")
public Object getObject() throws Exception {
return new Resource[0];
}
@TestAnnotation("some value")
public Class getObjectType() {
return Resource[].class;
}
public boolean isSingleton() {
return true;
}
}

View File

@ -0,0 +1,83 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
@Aspect
public class RetryAspect {
private int beginCalls;
private int commitCalls;
private int rollbackCalls;
@Pointcut("execution(public * UnreliableBean.*(..))")
public void execOfPublicMethod() {
}
/**
* Retry Advice
*/
@Around("execOfPublicMethod()")
public Object retry(ProceedingJoinPoint jp) throws Throwable {
boolean retry = true;
Object o = null;
while (retry) {
try {
retry = false;
this.beginCalls++;
try {
o = jp.proceed();
this.commitCalls++;
}
catch (RetryableException e) {
this.rollbackCalls++;
throw e;
}
}
catch (RetryableException re) {
retry = true;
}
}
return o;
}
public int getBeginCalls() {
return this.beginCalls;
}
public int getCommitCalls() {
return this.commitCalls;
}
public int getRollbackCalls() {
return this.rollbackCalls;
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import org.springframework.core.NestedRuntimeException;
/**
* @author Rob Harrop
* @since 2.0
*/
public class RetryableException extends NestedRuntimeException {
public RetryableException(String msg) {
super(msg);
}
public RetryableException(String msg, Throwable cause) {
super(msg, cause);
}
}

View File

@ -0,0 +1,30 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Created on 6 Oct 2006 by Adrian Colyer
*/
package org.springframework.aop.aspectj.autoproxy;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @author Adrian Colyer
* @since 2.0
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String value() ;
}

View File

@ -0,0 +1,41 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
import java.lang.reflect.Method;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.support.StaticMethodMatcherPointcutAdvisor;
import org.springframework.beans.ITestBean;
public class TestBeanAdvisor extends StaticMethodMatcherPointcutAdvisor {
public int count;
public TestBeanAdvisor() {
setAdvice(new MethodBeforeAdvice() {
public void before(Method method, Object[] args, Object target) throws Throwable {
++count;
}
});
}
public boolean matches(Method method, Class targetClass) {
return ITestBean.class.isAssignableFrom(targetClass);
}
}

View File

@ -0,0 +1,34 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy;
/**
* @author Rob Harrop
*/
public class UnreliableBean {
private int calls;
public int unreliable() {
this.calls++;
if (this.calls % 2 != 0) {
throw new RetryableException("foo");
}
return this.calls;
}
}

View File

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="testBean" class="org.springframework.beans.TestBean"/>
<bean id="aspect" class="org.springframework.aop.aspectj.autoproxy.ExceptionHandlingAspect"/>
</beans>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:config>
<aop:advisor advice-ref="testInterceptor" pointcut-ref="myPointcut"/>
</aop:config>
<bean id="testInterceptor" class="org.springframework.aop.aspectj.autoproxy.AnnotationPointcutTests$TestMethodInterceptor"/>
<bean id="myPointcut" class="org.springframework.aop.support.annotation.AnnotationMatchingPointcut" factory-method="forMethodAnnotation">
<constructor-arg value="org.springframework.aop.aspectj.autoproxy.TestAnnotation"/>
</bean>
<bean id="testAspect" class="org.springframework.aop.aspectj.autoproxy.AnnotationBindingTestAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.autoproxy.AnnotatedTestBeanImpl"/>
</beans>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:config>
<aop:aspect id="annotationBindingAspect" ref="testAspect">
<aop:around pointcut="@annotation(testAnnotation)" method="doWithAnnotation"/>
</aop:aspect>
</aop:config>
<bean id="testAspect" class="org.springframework.aop.aspectj.autoproxy.AnnotationBindingTestAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.autoproxy.AnnotatedTestBeanImpl"/>
</beans>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!--
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
-->
<aop:aspectj-autoproxy/>
<bean class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue">
<property name="multiple" value="2"/>
</bean>
<bean class="org.springframework.aop.aspectj.autoproxy.DummyAspect"/>
<bean class="org.springframework.aop.aspectj.autoproxy.DummyAspectWithParameter"/>
<bean id="adrianParent" abstract="true">
<property name="name" value="adrian"/>
</bean>
<bean id="adrian" class="org.springframework.beans.TestBean" parent="adrianParent">
<property name="age" value="34"/>
</bean>
<bean id="adrian2Parent" class="org.springframework.beans.TestBean" abstract="true">
<property name="name" value="adrian"/>
</bean>
<bean id="factoryBean" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="adrian"/>
<property name="targetMethod" value="toString"/>
</bean>
</beans>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<bean id="aspect" class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue">
<property name="multiple" value="3"/>
</bean>
<bean id="adrian" class="org.springframework.beans.TestBean">
<property name="name" value="Adrian"/>
<property name="age" value="34"/>
</bean>
<bean id="adrian2" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="Adrian"/>
<property name="age" value="34"/>
</bean>
<bean id="i21" class="org.springframework.beans.NestedTestBean" scope="prototype">
<property name="company" value="i21"/>
</bean>
<bean id="advisor" class="org.springframework.aop.aspectj.autoproxy.TestBeanAdvisor"/>
</beans>

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd"
default-lazy-init="true">
<aop:aspectj-autoproxy/>
<bean class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue">
<property name="multiple" value="2"/>
</bean>
<bean id="factoryBean" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="adrian"/>
<property name="targetMethod" value="toString"/>
</bean>
<bean id="adrianParent" abstract="true">
<property name="name" value="adrian"/>
</bean>
<bean id="adrian" class="org.springframework.beans.TestBean" parent="adrianParent">
<property name="age" value="34"/>
</bean>
<bean id="adrian2Parent" class="org.springframework.aop.aspectj.autoproxy.DummyFactoryBean" abstract="true"/>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!--
<bean
class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
-->
<aop:aspectj-autoproxy proxy-target-class="true"/>
</beans>

View File

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!--
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
-->
<aop:aspectj-autoproxy/>
<bean class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue">
<property name="multiple" value="2"/>
</bean>
<bean class="org.springframework.aop.aspectj.autoproxy.IncreaseReturnValue"/>
<bean id="adrian" class="org.springframework.beans.TestBean">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
</beans>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<aop:aspectj-autoproxy/>
<tx:annotation-driven/>
<bean id="transactionManager" class="org.springframework.transaction.CallCountingTransactionManager"/>
<bean id="testAspect" class="org.springframework.aop.aspectj.autoproxy.AtAspectJAnnotationBindingTestAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.autoproxy.AnnotatedTestBeanImpl"/>
<bean id="arrayFactoryBean" class="org.springframework.aop.aspectj.autoproxy.ResourceArrayFactoryBean"/>
</beans>

View File

@ -0,0 +1,168 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.benchmark;
import junit.framework.TestCase;
import org.springframework.aop.framework.Advised;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.ITestBean;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.util.StopWatch;
/**
* Tests for AspectJ auto proxying. Includes mixing with Spring AOP
* Advisors to demonstrate that existing autoproxying contract is honoured.
*
* @author Rod Johnson
*/
public class BenchmarkTests extends TestCase {
private static final String ASPECTJ_CONTEXT = "/org/springframework/aop/aspectj/autoproxy/benchmark/aspectj.xml";
private static final String SPRING_AOP_CONTEXT = "/org/springframework/aop/aspectj/autoproxy/benchmark/springAop.xml";
/**
* Change the return number to a higher number to make this test useful.
*/
protected int getCount() {
return 10;
}
public void testRepeatedAroundAdviceInvocationsWithAspectJ() {
testRepeatedAroundAdviceInvocations(ASPECTJ_CONTEXT, getCount(), "AspectJ");
}
public void testRepeatedAroundAdviceInvocationsWithSpringAop() {
testRepeatedAroundAdviceInvocations(SPRING_AOP_CONTEXT, getCount(), "Spring AOP");
}
public void testRepeatedBeforeAdviceInvocationsWithAspectJ() {
testBeforeAdviceWithoutJoinPoint(ASPECTJ_CONTEXT, getCount(), "AspectJ");
}
public void testRepeatedBeforeAdviceInvocationsWithSpringAop() {
testBeforeAdviceWithoutJoinPoint(SPRING_AOP_CONTEXT, getCount(), "Spring AOP");
}
public void testRepeatedAfterReturningAdviceInvocationsWithAspectJ() {
testAfterReturningAdviceWithoutJoinPoint(ASPECTJ_CONTEXT, getCount(), "AspectJ");
}
public void testRepeatedAfterReturningAdviceInvocationsWithSpringAop() {
testAfterReturningAdviceWithoutJoinPoint(SPRING_AOP_CONTEXT, getCount(), "Spring AOP");
}
public void testRepeatedMixWithAspectJ() {
testMix(ASPECTJ_CONTEXT, getCount(), "AspectJ");
}
public void testRepeatedMixWithSpringAop() {
testMix(SPRING_AOP_CONTEXT, getCount(), "Spring AOP");
}
private long testRepeatedAroundAdviceInvocations(String file, int howmany, String technology) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file);
StopWatch sw = new StopWatch();
sw.start(howmany + " repeated around advice invocations with " + technology);
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
assertEquals(68, adrian.getAge());
for (int i = 0; i < howmany; i++) {
adrian.getAge();
}
sw.stop();
System.out.println(sw.prettyPrint());
return sw.getLastTaskTimeMillis();
}
private long testBeforeAdviceWithoutJoinPoint(String file, int howmany, String technology) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file);
StopWatch sw = new StopWatch();
sw.start(howmany + " repeated before advice invocations with " + technology);
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
Advised a = (Advised) adrian;
assertTrue(a.getAdvisors().length >= 3);
assertEquals("adrian", adrian.getName());
for (int i = 0; i < howmany; i++) {
adrian.getName();
}
sw.stop();
System.out.println(sw.prettyPrint());
return sw.getLastTaskTimeMillis();
}
private long testAfterReturningAdviceWithoutJoinPoint(String file, int howmany, String technology) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file);
StopWatch sw = new StopWatch();
sw.start(howmany + " repeated after returning advice invocations with " + technology);
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
Advised a = (Advised) adrian;
assertTrue(a.getAdvisors().length >= 3);
// Hits joinpoint
adrian.setAge(25);
for (int i = 0; i < howmany; i++) {
adrian.setAge(i);
}
sw.stop();
System.out.println(sw.prettyPrint());
return sw.getLastTaskTimeMillis();
}
private long testMix(String file, int howmany, String technology) {
ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file);
StopWatch sw = new StopWatch();
sw.start(howmany + " repeated mixed invocations with " + technology);
ITestBean adrian = (ITestBean) bf.getBean("adrian");
assertTrue(AopUtils.isAopProxy(adrian));
Advised a = (Advised) adrian;
assertTrue(a.getAdvisors().length >= 3);
for (int i = 0; i < howmany; i++) {
// Hit all 3 joinpoints
adrian.getAge();
adrian.getName();
adrian.setAge(i);
// Invoke three non-advised methods
adrian.getDoctor();
adrian.getLawyer();
adrian.getSpouse();
}
sw.stop();
System.out.println(sw.prettyPrint());
return sw.getLastTaskTimeMillis();
}
}

View File

@ -0,0 +1,42 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.benchmark;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class MultiplyReturnValueInterceptor implements MethodInterceptor {
private int multiple = 2;
public int invocations;
public void setMultiple(int multiple) {
this.multiple = multiple;
}
public int getMultiple() {
return this.multiple;
}
public Object invoke(MethodInvocation mi) throws Throwable {
++invocations;
int result = (Integer) mi.proceed();
return result * this.multiple;
}
}

View File

@ -0,0 +1,51 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.benchmark;
import java.lang.reflect.Method;
import org.springframework.aop.Advisor;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
/**
*
*
* @author Rod Johnson
*
*/
public class TraceAfterReturningAdvice implements AfterReturningAdvice {
public int afterTakesInt;
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
++afterTakesInt;
}
public static Advisor advisor() {
return new DefaultPointcutAdvisor(
new StaticMethodMatcherPointcut() {
public boolean matches(Method method, Class targetClass) {
return method.getParameterTypes().length == 1 &&
method.getParameterTypes()[0].equals(Integer.class);
}
},
new TraceAfterReturningAdvice());
}
}

View File

@ -0,0 +1,40 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.benchmark;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
@Aspect
public class TraceAspect {
public int beforeStringReturn;
public int afterTakesInt;
@Before("execution(String *.*(..))")
public void traceWithoutJoinPoint() {
++beforeStringReturn;
}
@AfterReturning("execution(void *.*(int))")
public void traceWithoutJoinPoint2() {
++afterTakesInt;
}
}

View File

@ -0,0 +1,44 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.benchmark;
import java.lang.reflect.Method;
import org.springframework.aop.Advisor;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.StaticMethodMatcherPointcut;
public class TraceBeforeAdvice implements MethodBeforeAdvice {
public int beforeStringReturn;
public void before(Method method, Object[] args, Object target) throws Throwable {
++beforeStringReturn;
}
public static Advisor advisor() {
return new DefaultPointcutAdvisor(
new StaticMethodMatcherPointcut() {
public boolean matches(Method method, Class targetClass) {
return method.getReturnType().equals(String.class);
}
},
new TraceBeforeAdvice());
}
}

View File

@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!--
<bean
class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
-->
<aop:aspectj-autoproxy/>
<bean
class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue" >
<property name="multiple" value="2" />
</bean>
<bean
class="org.springframework.aop.aspectj.autoproxy.benchmark.TraceAspect" >
</bean>
<bean id="adrian" class="org.springframework.beans.TestBean">
<property name="name" value="adrian" />
<property name="age" value="34" />
</bean>
</beans>

View File

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!--
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator" />
-->
<aop:aspectj-autoproxy>
<!-- Explicit testing the whitespace body variant here -->
</aop:aspectj-autoproxy>
<bean class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor" >
<property name="advice" ref="multiplyReturnValueInterceptor" />
<property name="mappedName" value="getAge" />
</bean>
<bean id="multiplyReturnValueInterceptor"
class="org.springframework.aop.aspectj.autoproxy.benchmark.MultiplyReturnValueInterceptor" >
<property name="multiple" value="2" />
</bean>
<bean class="org.springframework.aop.aspectj.autoproxy.benchmark.TraceBeforeAdvice"
factory-method="advisor" />
<bean class="org.springframework.aop.aspectj.autoproxy.benchmark.TraceAfterReturningAdvice"
factory-method="advisor" />
<bean class="org.springframework.aop.aspectj.autoproxy.benchmark.TraceAspect"/>
<bean id="adrian" class="org.springframework.beans.TestBean">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
</beans>

View File

@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator">
<property name="customTargetSourceCreators">
<bean class="org.springframework.aop.framework.autoproxy.target.LazyInitTargetSourceCreator"/>
</property>
</bean>
<bean class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue">
<property name="multiple" value="2"/>
</bean>
<bean id="adrianParent" abstract="true">
<property name="name" value="adrian"/>
</bean>
<!-- parent="adrianParent" -->
<bean id="adrian" class="org.springframework.aop.aspectj.autoproxy.LazyTestBean" lazy-init="true">
<property name="age" value="34"/>
<property name="name" value="adrian"/>
</bean>
</beans>

View File

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<bean class="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests$PerTargetAspect"
scope="prototype">
<property name="order" value="5"/>
</bean>
<bean id="adrian" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
<bean id="juergen" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="juergen"/>
<property name="age" value="30"/>
</bean>
</beans>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<bean class="org.springframework.aop.aspectj.autoproxy.PerThisAspect" scope="prototype"/>
<bean id="adrian" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
</beans>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="retryAspect" class="org.springframework.aop.aspectj.autoproxy.RetryAspect"/>
<bean id="unreliableBean" class="org.springframework.aop.aspectj.autoproxy.UnreliableBean"/>
</beans>

View File

@ -0,0 +1,47 @@
/**
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.spr3064;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author acolyer
*
*/
public class SPR3064Tests extends AbstractDependencyInjectionSpringContextTests {
private Service service;
@Override
protected String[] getConfigLocations() {
return new String[] {"org/springframework/aop/aspectj/autoproxy/spr3064/annotationbinding-spr3064.xml"};
}
public void setService(Service service) {
this.service = service;
}
public void testServiceIsAdvised() {
try {
this.service.serveMe();
fail("service operation has not been advised by transaction interceptor");
}
catch(RuntimeException ex) {
assertEquals("advice invoked",ex.getMessage());
}
}
}

View File

@ -0,0 +1,26 @@
/**
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.spr3064;
/**
* @author acolyer
*
*/
public interface Service {
void serveMe();
}

View File

@ -0,0 +1,32 @@
/**
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.spr3064;
/**
* @author acolyer
*
*/
public class ServiceImpl implements Service {
/* (non-Javadoc)
* @see org.springframework.aop.aspectj.autoproxy.spr3064.Service#serveMe()
*/
@Transaction
public void serveMe() {
}
}

View File

@ -0,0 +1,28 @@
/**
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.spr3064;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* @author acolyer
*
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface Transaction {
}

View File

@ -0,0 +1,35 @@
/**
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.autoproxy.spr3064;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
/**
* @author acolyer
*
*/
@Aspect
public class TransactionInterceptor {
@Around(value="execution(* *..Service.*(..)) && @annotation(transaction)")
public Object around(ProceedingJoinPoint pjp, Transaction transaction) throws Throwable {
throw new RuntimeException("advice invoked");
//return pjp.proceed();
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="annotatedBean" class="org.springframework.aop.aspectj.autoproxy.spr3064.ServiceImpl"/>
<bean id="transactionInterceptor" class="org.springframework.aop.aspectj.autoproxy.spr3064.TransactionInterceptor"/>
</beans>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<bean id="aspect" class="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests$TwoAdviceAspect"/>
<bean id="adrian" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
</beans>

View File

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<bean id="aspect" class="org.springframework.aop.aspectj.annotation.AbstractAspectJAdvisorFactoryTests$TwoAdviceAspect"
scope="prototype"/>
<bean id="adrian" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
</beans>

View File

@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy>
<aop:include name="aspectOne"/>
</aop:aspectj-autoproxy>
<bean id="aspectOne" class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue" >
<property name="multiple" value="2" />
</bean>
<bean id="aspectTwo"
class="org.springframework.aop.aspectj.autoproxy.MultiplyReturnValue" >
<property name="multiple" value="2" />
</bean>
<bean id="adrian" class="org.springframework.beans.TestBean">
<property name="name" value="adrian" />
<property name="age" value="34" />
</bean>
</beans>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
<bean id="aspect" class="org.springframework.aop.aspectj.autoproxy.AdviceUsingThisJoinPoint"/>
<bean id="adrian" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name" value="adrian"/>
<property name="age" value="34"/>
</bean>
</beans>

View File

@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="testBean1" class="org.springframework.beans.TestBean"/>
<bean id="testBean2" class="org.springframework.beans.TestBean"/>
<bean id="testBean3" class="org.springframework.beans.TestBean"/>
<bean id="counterAspect" class="org.springframework.aop.aspectj.BeanNamePointcutAtAspectTests$CounterAspect"/>
</beans>

View File

@ -0,0 +1,169 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.generic;
import java.util.ArrayList;
import java.util.Collection;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.Employee;
import org.springframework.beans.TestBean;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests ensuring that after-returning advice for generic parameters bound to
* the advice and the return type follow AspectJ semantics.
*
* <p>See SPR-3628 for more details.
*
* @author Ramnivas Laddad
*/
public class AfterReturningGenericTypeMatchingTests extends AbstractDependencyInjectionSpringContextTests {
protected GenericReturnTypeVariationClass testBean;
protected CounterAspect counterAspect;
public AfterReturningGenericTypeMatchingTests() {
setPopulateProtectedVariables(true);
}
@Override
protected String getConfigPath() {
return "afterReturningGenericTypeMatchingTests-context.xml";
}
@Override
protected void onSetUp() throws Exception {
counterAspect.reset();
super.onSetUp();
}
public void testReturnTypeExactMatching() {
testBean.getStrings();
assertEquals(1, counterAspect.getStringsInvocationsCount);
assertEquals(0, counterAspect.getIntegersInvocationsCount);
counterAspect.reset();
testBean.getIntegers();
assertEquals(0, counterAspect.getStringsInvocationsCount);
assertEquals(1, counterAspect.getIntegersInvocationsCount);
}
public void testReturnTypeRawMatching() {
testBean.getStrings();
assertEquals(1, counterAspect.getRawsInvocationsCount);
counterAspect.reset();
testBean.getIntegers();
assertEquals(1, counterAspect.getRawsInvocationsCount);
}
public void testReturnTypeUpperBoundMatching() {
testBean.getIntegers();
assertEquals(1, counterAspect.getNumbersInvocationsCount);
}
public void testReturnTypeLowerBoundMatching() {
testBean.getTestBeans();
assertEquals(1, counterAspect.getTestBeanInvocationsCount);
counterAspect.reset();
testBean.getEmployees();
assertEquals(0, counterAspect.getTestBeanInvocationsCount);
}
public static class GenericReturnTypeVariationClass {
public Collection<String> getStrings() {
return new ArrayList<String>();
}
public Collection<Integer> getIntegers() {
return new ArrayList<Integer>();
}
public Collection<TestBean> getTestBeans() {
return new ArrayList<TestBean>();
}
public Collection<Employee> getEmployees() {
return new ArrayList<Employee>();
}
}
@Aspect
public static class CounterAspect {
private int getRawsInvocationsCount;
private int getStringsInvocationsCount;
private int getIntegersInvocationsCount;
private int getNumbersInvocationsCount;
private int getTestBeanInvocationsCount;
@Pointcut("execution(* org.springframework.aop.aspectj.generic.AfterReturningGenericTypeMatchingTests.GenericReturnTypeVariationClass.*(..))")
public void anyTestMethod() {
}
@AfterReturning(pointcut = "anyTestMethod()", returning = "ret")
public void incrementGetRawsInvocationsCount(Collection ret) {
getRawsInvocationsCount++;
}
@AfterReturning(pointcut = "anyTestMethod()", returning = "ret")
public void incrementGetStringsInvocationsCount(Collection<String> ret) {
getStringsInvocationsCount++;
}
@AfterReturning(pointcut = "anyTestMethod()", returning = "ret")
public void incrementGetIntegersInvocationsCount(Collection<Integer> ret) {
getIntegersInvocationsCount++;
}
@AfterReturning(pointcut = "anyTestMethod()", returning = "ret")
public void incrementGetNumbersInvocationsCount(Collection<? extends Number> ret) {
getNumbersInvocationsCount++;
}
@AfterReturning(pointcut = "anyTestMethod()", returning = "ret")
public void incrementTestBeanInvocationsCount(Collection<? super TestBean> ret) {
getTestBeanInvocationsCount++;
}
public void reset() {
getRawsInvocationsCount = 0;
getStringsInvocationsCount = 0;
getIntegersInvocationsCount = 0;
getNumbersInvocationsCount = 0;
getTestBeanInvocationsCount = 0;
}
}
}

View File

@ -0,0 +1,45 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.generic;
/**
* Tests for AspectJ pointcut expression matching when working with bridge methods.
*
* <p>This class focuses on class proxying.
*
* <p>See GenericBridgeMethodMatchingTests for more details.
*
* @author Ramnivas Laddad
*/
public class GenericBridgeMethodMatchingClassProxyTests extends GenericBridgeMethodMatchingTests {
@Override
protected String getConfigPath() {
return "genericBridgeMethodMatchingTests-classProxy-context.xml";
}
public void testGenericDerivedInterfaceMethodThroughClass() {
((DerivedStringParameterizedClass) testBean).genericDerivedInterfaceMethod("");
assertEquals(1, counterAspect.count);
}
public void testGenericBaseInterfaceMethodThroughClass() {
((DerivedStringParameterizedClass) testBean).genericBaseInterfaceMethod("");
assertEquals(1, counterAspect.count);
}
}

View File

@ -0,0 +1,103 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.generic;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests for AspectJ pointcut expression matching when working with bridge methods.
*
* <p>Depending on the caller's static type either the bridge method or the user-implemented method
* gets called as the way into the proxy. Therefore, we need tests for calling a bean with
* static type set to type with generic method and to type with specific non-generic implementation.
*
* <p>This class focuses on JDK proxy, while a subclass, GenericBridgeMethodMatchingClassProxyTests,
* focuses on class proxying.
*
* See SPR-3556 for more details.
*
* @author Ramnivas Laddad
*/
public class GenericBridgeMethodMatchingTests extends AbstractDependencyInjectionSpringContextTests {
protected DerivedInterface<String> testBean;
protected CounterAspect counterAspect;
public GenericBridgeMethodMatchingTests() {
setPopulateProtectedVariables(true);
}
@Override
protected String getConfigPath() {
return "genericBridgeMethodMatchingTests-context.xml";
}
@Override
protected void onSetUp() throws Exception {
counterAspect.count = 0;
super.onSetUp();
}
public void testGenericDerivedInterfaceMethodThroughInterface() {
testBean.genericDerivedInterfaceMethod("");
assertEquals(1, counterAspect.count);
}
public void testGenericBaseInterfaceMethodThroughInterface() {
testBean.genericBaseInterfaceMethod("");
assertEquals(1, counterAspect.count);
}
public interface BaseInterface<T> {
void genericBaseInterfaceMethod(T t);
}
public interface DerivedInterface<T> extends BaseInterface<T> {
public void genericDerivedInterfaceMethod(T t);
}
public static class DerivedStringParameterizedClass implements DerivedInterface<String> {
public void genericDerivedInterfaceMethod(String t) {
}
public void genericBaseInterfaceMethod(String t) {
}
}
@Aspect
public static class CounterAspect {
public int count;
@Before("execution(* *..BaseInterface+.*(..))")
public void increment() {
count++;
}
}
}

View File

@ -0,0 +1,129 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.aop.aspectj.generic;
import java.util.Collection;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* Tests that poitncut matching is correct with generic method parameter.
* See SPR-3904 for more details.
*
* @author Ramnivas Laddad
*/
public class GenericParameterMatchingTests extends AbstractDependencyInjectionSpringContextTests {
protected CounterAspect counterAspect;
protected GenericInterface<String> testBean;
public GenericParameterMatchingTests() {
setPopulateProtectedVariables(true);
}
@Override
protected String getConfigPath() {
return "genericParameterMatchingTests-context.xml";
}
@Override
protected void onSetUp() throws Exception {
counterAspect.reset();
super.onSetUp();
}
public void testGenericInterfaceGenericArgExecution() {
testBean.save("");
assertEquals(1, counterAspect.genericInterfaceGenericArgExecutionCount);
}
public void testGenericInterfaceGenericCollectionArgExecution() {
testBean.saveAll(null);
// TODO: uncomment once we officially update to AspectJ 1.6.0
//assertEquals(1, counterAspect.genericInterfaceGenericCollectionArgExecutionCount);
}
public void testGenericInterfaceSubtypeGenericCollectionArgExecution() {
testBean.saveAll(null);
assertEquals(1, counterAspect.genericInterfaceSubtypeGenericCollectionArgExecutionCount);
}
static interface GenericInterface<T> {
public void save(T bean);
public void saveAll(Collection<T> beans);
}
static class GenericImpl<T> implements GenericInterface<T> {
public void save(T bean) {
}
public void saveAll(Collection<T> beans) {
}
}
@Aspect
public static class CounterAspect {
int genericInterfaceGenericArgExecutionCount;
int genericInterfaceGenericCollectionArgExecutionCount;
int genericInterfaceSubtypeGenericCollectionArgExecutionCount;
public void reset() {
genericInterfaceGenericArgExecutionCount = 0;
genericInterfaceGenericCollectionArgExecutionCount = 0;
genericInterfaceSubtypeGenericCollectionArgExecutionCount = 0;
}
@Pointcut("execution(* org.springframework.aop.aspectj.generic.GenericParameterMatchingTests.GenericInterface.save(..))")
public void genericInterfaceGenericArgExecution() {}
@Pointcut("execution(* org.springframework.aop.aspectj.generic.GenericParameterMatchingTests.GenericInterface.saveAll(..))")
public void GenericInterfaceGenericCollectionArgExecution() {}
@Pointcut("execution(* org.springframework.aop.aspectj.generic.GenericParameterMatchingTests.GenericInterface+.saveAll(..))")
public void genericInterfaceSubtypeGenericCollectionArgExecution() {}
@Before("genericInterfaceGenericArgExecution()")
public void incrementGenericInterfaceGenericArgExecution() {
genericInterfaceGenericArgExecutionCount++;
}
@Before("GenericInterfaceGenericCollectionArgExecution()")
public void incrementGenericInterfaceGenericCollectionArgExecution() {
genericInterfaceGenericCollectionArgExecutionCount++;
}
@Before("genericInterfaceSubtypeGenericCollectionArgExecution()")
public void incrementGenericInterfaceSubtypeGenericCollectionArgExecution() {
genericInterfaceSubtypeGenericCollectionArgExecutionCount++;
}
}
}

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="counterAspect" class="org.springframework.aop.aspectj.generic.AfterReturningGenericTypeMatchingTests$CounterAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.generic.AfterReturningGenericTypeMatchingTests$GenericReturnTypeVariationClass"/>
</beans>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="true"/>
<bean id="counterAspect" class="org.springframework.aop.aspectj.generic.GenericBridgeMethodMatchingTests$CounterAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.generic.GenericBridgeMethodMatchingTests$DerivedStringParameterizedClass"/>
</beans>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="false"/>
<bean id="counterAspect" class="org.springframework.aop.aspectj.generic.GenericBridgeMethodMatchingTests$CounterAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.generic.GenericBridgeMethodMatchingTests$DerivedStringParameterizedClass"/>
</beans>

View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="counterAspect" class="org.springframework.aop.aspectj.generic.GenericParameterMatchingTests$CounterAspect"/>
<bean id="testBean" class="org.springframework.aop.aspectj.generic.GenericParameterMatchingTests$GenericImpl"/>
</beans>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="testBean" class="org.springframework.beans.TestBean">
<property name="name" value="aTestBean"/>
</bean>
<aop:aspectj-autoproxy proxy-target-class="true">
<aop:include name="counterAtAspectJAspect"/>
</aop:aspectj-autoproxy>
<bean id="counterAtAspectJAspect"
class="org.springframework.aop.aspectj.ImplicitJPArgumentMatchingAtAspectJTests$CounterAtAspectJAspect"/>
</beans>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:config>
<aop:aspect ref="monitoringAspect">
<aop:before method="before" pointcut="execution(* increment*())" />
<aop:around method="around" pointcut="execution(* increment*())" />
</aop:aspect>
</aop:config>
<bean id="monitoringAspect" class="org.springframework.aop.aspectj.JoinPointMonitorAspect">
<property name="counter" ref="counter"/>
</bean>
<bean id="counter" class="org.springframework.aop.aspectj.Counter"/>
</beans>

View File

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="counter" class="org.springframework.aop.aspectj.Counter"/>
<aop:config>
<aop:aspect ref="monitoringAspect">
<aop:before method="before" pointcut="execution(* increment*())" />
<aop:around method="around" pointcut="execution(* increment*())" />
</aop:aspect>
</aop:config>
<bean id="monitoringAspect" class="org.springframework.aop.aspectj.JoinPointMonitorAspect" lazy-init="true">
<property name="counter" ref="counter"/>
</bean>
</beans>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<bean id="counter" class="org.springframework.aop.aspectj.Counter"/>
<aop:aspectj-autoproxy/>
<bean id="monitoringAspect" class="org.springframework.aop.aspectj.JoinPointMonitorAtAspectJAspect">
<property name="counter" ref="counter" />
</bean>
</beans>

View File

@ -0,0 +1,18 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy/>
<bean id="monitoringAspect"
class="org.springframework.aop.aspectj.JoinPointMonitorAtAspectJAspect">
<property name="counter" ref="counter" />
</bean>
<bean id="counter" class="org.springframework.aop.aspectj.Counter"/>
</beans>

View File

@ -0,0 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<aop:aspectj-autoproxy proxy-target-class="false"/>
<bean id="counter"
class="org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests$Counter" />
<bean id="testBean" class="org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests$TestImpl" />
<bean id="testAnnotatedClassBean" class="org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests$AnnotatedClassTestImpl" />
<bean id="testAnnotatedMethodBean" class="org.springframework.aop.aspectj.ThisAndTargetSelectionOnlyPointcutsAtAspectJTests$AnnotatedMethodTestImpl" />
</beans>

View File

@ -0,0 +1,30 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
/**
* @author Juergen Hoeller
*/
public enum CustomEnum {
VALUE_1, VALUE_2;
public String toString() {
return "CustomEnum: " + name();
}
}

View File

@ -0,0 +1,237 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.springframework.core.io.Resource;
/**
* @author Juergen Hoeller
*/
public class GenericBean<T> {
private Set<Integer> integerSet;
private List<Resource> resourceList;
private List<List<Integer>> listOfLists;
private ArrayList<String[]> listOfArrays;
private List<Map<Integer, Long>> listOfMaps;
private Map plainMap;
private Map<Short, Integer> shortMap;
private HashMap<Long, ?> longMap;
private Map<Number, Collection<? extends Object>> collectionMap;
private Map<String, Map<Integer, Long>> mapOfMaps;
private Map<Integer, List<Integer>> mapOfLists;
private CustomEnum customEnum;
private T genericProperty;
private List<T> genericListProperty;
public GenericBean() {
}
public GenericBean(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
public GenericBean(Set<Integer> integerSet, List<Resource> resourceList) {
this.integerSet = integerSet;
this.resourceList = resourceList;
}
public GenericBean(HashSet<Integer> integerSet, Map<Short, Integer> shortMap) {
this.integerSet = integerSet;
this.shortMap = shortMap;
}
public GenericBean(Map<Short, Integer> shortMap, Resource resource) {
this.shortMap = shortMap;
this.resourceList = Collections.singletonList(resource);
}
public GenericBean(Map plainMap, Map<Short, Integer> shortMap) {
this.plainMap = plainMap;
this.shortMap = shortMap;
}
public GenericBean(HashMap<Long, ?> longMap) {
this.longMap = longMap;
}
public GenericBean(boolean someFlag, Map<Number, Collection<? extends Object>> collectionMap) {
this.collectionMap = collectionMap;
}
public Set<Integer> getIntegerSet() {
return integerSet;
}
public void setIntegerSet(Set<Integer> integerSet) {
this.integerSet = integerSet;
}
public List<Resource> getResourceList() {
return resourceList;
}
public void setResourceList(List<Resource> resourceList) {
this.resourceList = resourceList;
}
public List<List<Integer>> getListOfLists() {
return listOfLists;
}
public ArrayList<String[]> getListOfArrays() {
return listOfArrays;
}
public void setListOfArrays(ArrayList<String[]> listOfArrays) {
this.listOfArrays = listOfArrays;
}
public void setListOfLists(List<List<Integer>> listOfLists) {
this.listOfLists = listOfLists;
}
public List<Map<Integer, Long>> getListOfMaps() {
return listOfMaps;
}
public void setListOfMaps(List<Map<Integer, Long>> listOfMaps) {
this.listOfMaps = listOfMaps;
}
public Map getPlainMap() {
return plainMap;
}
public Map<Short, Integer> getShortMap() {
return shortMap;
}
public void setShortMap(Map<Short, Integer> shortMap) {
this.shortMap = shortMap;
}
public HashMap<Long, ?> getLongMap() {
return longMap;
}
public void setLongMap(HashMap<Long, ?> longMap) {
this.longMap = longMap;
}
public Map<Number, Collection<? extends Object>> getCollectionMap() {
return collectionMap;
}
public void setCollectionMap(Map<Number, Collection<? extends Object>> collectionMap) {
this.collectionMap = collectionMap;
}
public Map<String, Map<Integer, Long>> getMapOfMaps() {
return mapOfMaps;
}
public void setMapOfMaps(Map<String, Map<Integer, Long>> mapOfMaps) {
this.mapOfMaps = mapOfMaps;
}
public Map<Integer, List<Integer>> getMapOfLists() {
return mapOfLists;
}
public void setMapOfLists(Map<Integer, List<Integer>> mapOfLists) {
this.mapOfLists = mapOfLists;
}
public T getGenericProperty() {
return genericProperty;
}
public void setGenericProperty(T genericProperty) {
this.genericProperty = genericProperty;
}
public List<T> getGenericListProperty() {
return genericListProperty;
}
public void setGenericListProperty(List<T> genericListProperty) {
this.genericListProperty = genericListProperty;
}
public CustomEnum getCustomEnum() {
return customEnum;
}
public void setCustomEnum(CustomEnum customEnum) {
this.customEnum = customEnum;
}
public static GenericBean createInstance(Set<Integer> integerSet) {
return new GenericBean(integerSet);
}
public static GenericBean createInstance(Set<Integer> integerSet, List<Resource> resourceList) {
return new GenericBean(integerSet, resourceList);
}
public static GenericBean createInstance(HashSet<Integer> integerSet, Map<Short, Integer> shortMap) {
return new GenericBean(integerSet, shortMap);
}
public static GenericBean createInstance(Map<Short, Integer> shortMap, Resource resource) {
return new GenericBean(shortMap, resource);
}
public static GenericBean createInstance(Map map, Map<Short, Integer> shortMap) {
return new GenericBean(map, shortMap);
}
public static GenericBean createInstance(HashMap<Long, ?> longMap) {
return new GenericBean(longMap);
}
public static GenericBean createInstance(boolean someFlag, Map<Number, Collection<? extends Object>> collectionMap) {
return new GenericBean(someFlag, collectionMap);
}
}

View File

@ -0,0 +1,24 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
/**
* @author Juergen Hoeller
*/
public class GenericIntegerBean extends GenericBean<Integer> {
}

View File

@ -0,0 +1,26 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.util.Set;
/**
* @author Juergen Hoeller
*/
public class GenericSetOfIntegerBean extends GenericBean<Set<Integer>> {
}

View File

@ -0,0 +1,80 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory.annotation;
import junit.framework.TestCase;
import org.springframework.beans.factory.wiring.BeanWiringInfo;
/**
* @author Rick Evans
*/
public class AnnotationBeanWiringInfoResolverTests extends TestCase {
public void testResolveWiringInfo() throws Exception {
try {
new AnnotationBeanWiringInfoResolver().resolveWiringInfo(null);
fail("Must have thrown an IllegalArgumentException by this point (null argument)");
}
catch (IllegalArgumentException expected) {
}
}
public void testResolveWiringInfoWithAnInstanceOfANonAnnotatedClass() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo("java.lang.String is not @Configurable");
assertNull("Must be returning null for a non-@Configurable class instance", info);
}
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClass() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new Soap());
assertNotNull("Must *not* be returning null for a non-@Configurable class instance", info);
}
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitly() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new WirelessSoap());
assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info);
assertFalse(info.indicatesAutowiring());
assertEquals(WirelessSoap.class.getName(), info.getBeanName());
}
public void testResolveWiringInfoWithAnInstanceOfAnAnnotatedClassWithAutowiringTurnedOffExplicitlyAndCustomBeanName() {
AnnotationBeanWiringInfoResolver resolver = new AnnotationBeanWiringInfoResolver();
BeanWiringInfo info = resolver.resolveWiringInfo(new NamedWirelessSoap());
assertNotNull("Must *not* be returning null for an @Configurable class instance even when autowiring is NO", info);
assertFalse(info.indicatesAutowiring());
assertEquals("DerBigStick", info.getBeanName());
}
@Configurable()
private static class Soap {
}
@Configurable(autowire = Autowire.NO)
private static class WirelessSoap {
}
@Configurable(autowire = Autowire.NO, value = "DerBigStick")
private static class NamedWirelessSoap {
}
}

Some files were not shown because too many files have changed in this diff Show More