Java Code Examples for org.springframework.aop.Advisor

The following examples show how to use org.springframework.aop.Advisor. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: spring-analysis-note   Source File: AbstractAopProxyTests.java    License: MIT License 6 votes vote down vote up
/**
 * Check that the string is informative.
 */
@Test
public void testProxyConfigString() {
	TestBean target = new TestBean();
	ProxyFactory pc = new ProxyFactory(target);
	pc.setInterfaces(ITestBean.class);
	pc.addAdvice(new NopInterceptor());
	MethodBeforeAdvice mba = new CountingBeforeAdvice();
	Advisor advisor = new DefaultPointcutAdvisor(new NameMatchMethodPointcut(), mba);
	pc.addAdvisor(advisor);
	ITestBean proxied = (ITestBean) createProxy(pc);

	String proxyConfigString = ((Advised) proxied).toProxyConfigString();
	assertTrue(proxyConfigString.contains(advisor.toString()));
	assertTrue(proxyConfigString.contains("1 interface"));
}
 
Example 2
@Test
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);
	}
}
 
Example 3
/**
 * Sort the rest by AspectJ precedence. If two pieces of advice have
 * come from the same aspect they will have the same order.
 * Advice from the same aspect is then further ordered according to the
 * following rules:
 * <ul>
 * <li>if either of the pair is after advice, then the advice declared
 * last gets highest precedence (runs last)</li>
 * <li>otherwise the advice declared first gets highest precedence (runs first)</li>
 * </ul>
 * <p><b>Important:</b> Advisors are sorted in precedence order, from highest
 * precedence to lowest. "On the way in" to a join point, the highest precedence
 * advisor should run first. "On the way out" of a join point, the highest precedence
 * advisor should run last.
 */
@Override
@SuppressWarnings("unchecked")
protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
	List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = new ArrayList<>(advisors.size());
	for (Advisor element : advisors) {
		partiallyComparableAdvisors.add(
				new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR));
	}
	List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors);
	if (sorted != null) {
		List<Advisor> result = new ArrayList<>(advisors.size());
		for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) {
			result.add(pcAdvisor.getAdvisor());
		}
		return result;
	}
	else {
		return super.sortAdvisors(advisors);
	}
}
 
Example 4
Source Project: java-technology-stack   Source File: GroovyAspectTests.java    License: MIT License 6 votes vote down vote up
private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message,
		boolean proxyTargetClass) throws Exception {

	logAdvice.reset();

	ProxyFactory factory = new ProxyFactory(target);
	factory.setProxyTargetClass(proxyTargetClass);
	factory.addAdvisor(advisor);
	TestService bean = (TestService) factory.getProxy();

	assertEquals(0, logAdvice.getCountThrows());
	try {
		bean.sayHello();
		fail("Expected exception");
	}
	catch (TestException ex) {
		assertEquals(message, ex.getMessage());
	}
	assertEquals(1, logAdvice.getCountThrows());
}
 
Example 5
protected Object createProxy(Object target, List<Advisor> 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);
	pf.addAdvisors(advisors);

	pf.setExposeProxy(true);
	return pf.getProxy();
}
 
Example 6
Source Project: spring-analysis-note   Source File: GroovyAspectTests.java    License: MIT License 6 votes vote down vote up
private void testAdvice(Advisor advisor, LogUserAdvice logAdvice, TestService target, String message,
		boolean proxyTargetClass) throws Exception {

	logAdvice.reset();

	ProxyFactory factory = new ProxyFactory(target);
	factory.setProxyTargetClass(proxyTargetClass);
	factory.addAdvisor(advisor);
	TestService bean = (TestService) factory.getProxy();

	assertEquals(0, logAdvice.getCountThrows());
	try {
		bean.sayHello();
		fail("Expected exception");
	}
	catch (TestException ex) {
		assertEquals(message, ex.getMessage());
	}
	assertEquals(1, logAdvice.getCountThrows());
}
 
Example 7
@Override
public MethodInterceptor[] getInterceptors(Advisor advisor) throws UnknownAdviceTypeException {
	List<MethodInterceptor> interceptors = new ArrayList<>(3);
	Advice advice = advisor.getAdvice();
	if (advice instanceof MethodInterceptor) {
		interceptors.add((MethodInterceptor) advice);
	}
	for (AdvisorAdapter adapter : this.adapters) {
		if (adapter.supportsAdvice(advice)) {
			interceptors.add(adapter.getInterceptor(advisor));
		}
	}
	if (interceptors.isEmpty()) {
		throw new UnknownAdviceTypeException(advisor.getAdvice());
	}
	return interceptors.toArray(new MethodInterceptor[0]);
}
 
Example 8
/**
 * Build a {@link org.springframework.aop.aspectj.DeclareParentsAdvisor}
 * for the given introduction field.
 * <p>Resulting Advisors will need to be evaluated for targets.
 * @param introductionField the field to introspect
 * @return the Advisor instance, or {@code null} if not an Advisor
 */
@Nullable
private Advisor getDeclareParentsAdvisor(Field introductionField) {
	DeclareParents declareParents = introductionField.getAnnotation(DeclareParents.class);
	if (declareParents == null) {
		// Not an introduction field
		return null;
	}

	if (DeclareParents.class == declareParents.defaultImpl()) {
		throw new IllegalStateException("'defaultImpl' attribute must be set on DeclareParents");
	}

	return new DeclareParentsAdvisor(
			introductionField.getType(), declareParents.value(), declareParents.defaultImpl());
}
 
Example 9
@Test
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);
	}
}
 
Example 10
/**
 * Sort the rest by AspectJ precedence. If two pieces of advice have
 * come from the same aspect they will have the same order.
 * Advice from the same aspect is then further ordered according to the
 * following rules:
 * <ul>
 * <li>if either of the pair is after advice, then the advice declared
 * last gets highest precedence (runs last)</li>
 * <li>otherwise the advice declared first gets highest precedence (runs first)</li>
 * </ul>
 * <p><b>Important:</b> Advisors are sorted in precedence order, from highest
 * precedence to lowest. "On the way in" to a join point, the highest precedence
 * advisor should run first. "On the way out" of a join point, the highest precedence
 * advisor should run last.
 */
@Override
@SuppressWarnings("unchecked")
protected List<Advisor> sortAdvisors(List<Advisor> advisors) {
	List<PartiallyComparableAdvisorHolder> partiallyComparableAdvisors = new ArrayList<>(advisors.size());
	for (Advisor element : advisors) {
		partiallyComparableAdvisors.add(
				new PartiallyComparableAdvisorHolder(element, DEFAULT_PRECEDENCE_COMPARATOR));
	}
	List<PartiallyComparableAdvisorHolder> sorted = PartialOrder.sort(partiallyComparableAdvisors);
	if (sorted != null) {
		List<Advisor> result = new ArrayList<>(advisors.size());
		for (PartiallyComparableAdvisorHolder pcAdvisor : sorted) {
			result.add(pcAdvisor.getAdvisor());
		}
		return result;
	}
	else {
		return super.sortAdvisors(advisors);
	}
}
 
Example 11
protected Object createProxy(Object target, List<Advisor> 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);
	pf.addAdvisors(advisors);

	pf.setExposeProxy(true);
	return pf.getProxy();
}
 
Example 12
@Test
public void testSameAspectNoAfterAdvice() {
	Advisor advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
	Advisor advisor2 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
	assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2));

	advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
	advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
	assertEquals("advisor2 sorted before advisor1", 1, this.comparator.compare(advisor1, advisor2));
}
 
Example 13
Source Project: java-technology-stack   Source File: AdvisedSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Count advices of the given class.
 * @param adviceClass the advice class to check
 * @return the count of the interceptors of this class or subclasses
 */
public int countAdvicesOfType(@Nullable Class<?> adviceClass) {
	int count = 0;
	if (adviceClass != null) {
		for (Advisor advisor : this.advisors) {
			if (adviceClass.isInstance(advisor.getAdvice())) {
				count++;
			}
		}
	}
	return count;
}
 
Example 14
Source Project: java-technology-stack   Source File: ProxyFactoryTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testReplaceAdvisor() {
	TestBean target = new TestBean();
	ProxyFactory pf = new ProxyFactory(target);
	NopInterceptor nop = new NopInterceptor();
	CountingBeforeAdvice cba1 = new CountingBeforeAdvice();
	CountingBeforeAdvice cba2 = new CountingBeforeAdvice();
	Advisor advisor1 = new DefaultPointcutAdvisor(cba1);
	Advisor advisor2 = new DefaultPointcutAdvisor(cba2);
	pf.addAdvisor(advisor1);
	pf.addAdvice(nop);
	ITestBean proxied = (ITestBean) pf.getProxy();
	// Use the type cast feature
	// Replace etc methods on advised should be same as on ProxyFactory
	Advised advised = (Advised) proxied;
	proxied.setAge(5);
	assertEquals(1, cba1.getCalls());
	assertEquals(0, cba2.getCalls());
	assertEquals(1, nop.getCount());
	assertFalse(advised.replaceAdvisor(new DefaultPointcutAdvisor(new NopInterceptor()), advisor2));
	assertTrue(advised.replaceAdvisor(advisor1, advisor2));
	assertEquals(advisor2, pf.getAdvisors()[0]);
	assertEquals(5, proxied.getAge());
	assertEquals(1, cba1.getCalls());
	assertEquals(2, nop.getCount());
	assertEquals(1, cba2.getCalls());
	assertFalse(pf.replaceAdvisor(new DefaultPointcutAdvisor(null), advisor1));
}
 
Example 15
@Test
public void testIntroductionBasedOnAnnotationMatch_SPR5307() {
	AnnotatedTarget target = new AnnotatedTargetImpl();
	List<Advisor> advisors = getFixture().getAdvisors(
			new SingletonMetadataAwareAspectInstanceFactory(new MakeAnnotatedTypeModifiable(), "someBean"));
	Object proxy = createProxy(target, advisors, AnnotatedTarget.class);
	System.out.println(advisors.get(1));
	assertTrue(proxy instanceof Lockable);
	Lockable lockable = (Lockable)proxy;
	lockable.locked();
}
 
Example 16
@Test
public void testProxyingDecorator() throws Exception {
	ITestBean bean = (ITestBean) this.beanFactory.getBean("debuggingTestBean");
	assertTestBean(bean);
	assertTrue(AopUtils.isAopProxy(bean));
	Advisor[] advisors = ((Advised) bean).getAdvisors();
	assertEquals("Incorrect number of advisors", 1, advisors.length);
	assertEquals("Incorrect advice class", DebugInterceptor.class, advisors[0].getAdvice().getClass());
}
 
Example 17
protected void checkWillTranslateExceptions(Object o) {
	assertTrue(o instanceof Advised);
	Advised a = (Advised) o;
	for (Advisor advisor : a.getAdvisors()) {
		if (advisor instanceof PersistenceExceptionTranslationAdvisor) {
			return;
		}
	}
	fail("No translation");
}
 
Example 18
Source Project: java-technology-stack   Source File: AspectJAopUtils.java    License: MIT License 5 votes vote down vote up
/**
 * Return {@code true} if the advisor is a form of after advice.
 */
public static boolean isAfterAdvice(Advisor anAdvisor) {
	AspectJPrecedenceInformation precedenceInfo = getAspectJPrecedenceInformationFor(anAdvisor);
	if (precedenceInfo != null) {
		return precedenceInfo.isAfterAdvice();
	}
	return (anAdvisor.getAdvice() instanceof AfterAdvice);
}
 
Example 19
Source Project: spring-analysis-note   Source File: AspectJPrecedenceComparator.java    License: MIT License 5 votes vote down vote up
private int comparePrecedenceWithinAspect(Advisor advisor1, Advisor advisor2) {
	boolean oneOrOtherIsAfterAdvice =
			(AspectJAopUtils.isAfterAdvice(advisor1) || AspectJAopUtils.isAfterAdvice(advisor2));
	int adviceDeclarationOrderDelta = getAspectDeclarationOrder(advisor1) - getAspectDeclarationOrder(advisor2);

	if (oneOrOtherIsAfterAdvice) {
		// the advice declared last has higher precedence
		if (adviceDeclarationOrderDelta < 0) {
			// advice1 was declared before advice2
			// so advice1 has lower precedence
			return LOWER_PRECEDENCE;
		}
		else if (adviceDeclarationOrderDelta == 0) {
			return SAME_PRECEDENCE;
		}
		else {
			return HIGHER_PRECEDENCE;
		}
	}
	else {
		// the advice declared first has higher precedence
		if (adviceDeclarationOrderDelta < 0) {
			// advice1 was declared before advice2
			// so advice1 has higher precedence
			return HIGHER_PRECEDENCE;
		}
		else if (adviceDeclarationOrderDelta == 0) {
			return SAME_PRECEDENCE;
		}
		else {
			return LOWER_PRECEDENCE;
		}
	}
}
 
Example 20
@Test
public void testMultiplePerTargetAspects() throws SecurityException, NoSuchMethodException {
	TestBean target = new TestBean();
	int realAge = 65;
	target.setAge(realAge);

	List<Advisor> advisors = new LinkedList<>();
	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());
}
 
Example 21
Source Project: spring-analysis-note   Source File: AspectJPrecedenceComparator.java    License: MIT License 5 votes vote down vote up
private int getAspectDeclarationOrder(Advisor anAdvisor) {
	AspectJPrecedenceInformation precedenceInfo =
		AspectJAopUtils.getAspectJPrecedenceInformationFor(anAdvisor);
	if (precedenceInfo != null) {
		return precedenceInfo.getDeclarationOrder();
	}
	else {
		return 0;
	}
}
 
Example 22
Source Project: java-technology-stack   Source File: AdvisedSupport.java    License: MIT License 5 votes vote down vote up
@Override
public boolean replaceAdvisor(Advisor a, Advisor b) throws AopConfigException {
	Assert.notNull(a, "Advisor a must not be null");
	Assert.notNull(b, "Advisor b must not be null");
	int index = indexOf(a);
	if (index == -1) {
		return false;
	}
	removeAdvisor(index);
	addAdvisor(index, b);
	return true;
}
 
Example 23
Source Project: java-technology-stack   Source File: BenchmarkTests.java    License: MIT License 5 votes vote down vote up
public static Advisor advisor() {
	return new DefaultPointcutAdvisor(
		new StaticMethodMatcherPointcut() {
			@Override
			public boolean matches(Method method, Class<?> targetClass) {
				return method.getReturnType().equals(String.class);
			}
		},
		new TraceBeforeAdvice());
}
 
Example 24
Source Project: java-technology-stack   Source File: AdvisedSupport.java    License: MIT License 5 votes vote down vote up
@Override
public boolean removeAdvisor(Advisor advisor) {
	int index = indexOf(advisor);
	if (index == -1) {
		return false;
	}
	else {
		removeAdvisor(index);
		return true;
	}
}
 
Example 25
Source Project: java-technology-stack   Source File: AspectJProxyFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Add all {@link Advisor Advisors} from the supplied {@link MetadataAwareAspectInstanceFactory}
 * to the current chain. Exposes any special purpose {@link Advisor Advisors} if needed.
 * @see AspectJProxyUtils#makeAdvisorChainAspectJCapableIfNecessary(List)
 */
private void addAdvisorsFromAspectInstanceFactory(MetadataAwareAspectInstanceFactory instanceFactory) {
	List<Advisor> advisors = this.aspectFactory.getAdvisors(instanceFactory);
	Class<?> targetClass = getTargetClass();
	Assert.state(targetClass != null, "Unresolvable target class");
	advisors = AopUtils.findAdvisorsThatCanApply(advisors, targetClass);
	AspectJProxyUtils.makeAdvisorChainAspectJCapableIfNecessary(advisors);
	AnnotationAwareOrderComparator.sort(advisors);
	addAdvisors(advisors);
}
 
Example 26
@Test
public void testHigherAdvisorPrecedenceAfterAdvice() {
	Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
	Advisor advisor2 = createAspectJAroundAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect");
	assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2));

	advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
	advisor2 = createAspectJAfterThrowingAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
	assertEquals("advisor2 sorted after advisor1", -1, this.comparator.compare(advisor1, advisor2));
}
 
Example 27
@Test
public void testHigherAdvisorPrecedenceNoAfterAdvice() {
	Advisor advisor1 = createSpringAOPBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER);
	Advisor advisor2 = createAspectJBeforeAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
	assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2));

	advisor1 = createAspectJBeforeAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
	advisor2 = createAspectJAroundAdvice(LOW_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
	assertEquals("advisor1 sorted before advisor2", -1, this.comparator.compare(advisor1, advisor2));
}
 
Example 28
Source Project: spring-analysis-note   Source File: DefaultAdvisorChainFactory.java    License: MIT License 5 votes vote down vote up
/**
 * Determine whether the Advisors contain matching introductions.
 */
private static boolean hasMatchingIntroductions(Advisor[] advisors, Class<?> actualClass) {
	for (Advisor advisor : advisors) {
		if (advisor instanceof IntroductionAdvisor) {
			IntroductionAdvisor ia = (IntroductionAdvisor) advisor;
			if (ia.getClassFilter().matches(actualClass)) {
				return true;
			}
		}
	}
	return false;
}
 
Example 29
@Test
public void testSameAdvisorPrecedenceDifferentAspectAfterAdvice() {
	Advisor advisor1 = createAspectJAfterAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someAspect");
	Advisor advisor2 = createAspectJAroundAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someOtherAspect");
	assertEquals("nothing to say about order here", 0, this.comparator.compare(advisor1, advisor2));

	advisor1 = createAspectJAfterReturningAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, LATE_ADVICE_DECLARATION_ORDER, "someAspect");
	advisor2 = createAspectJAfterThrowingAdvice(HIGH_PRECEDENCE_ADVISOR_ORDER, EARLY_ADVICE_DECLARATION_ORDER, "someOtherAspect");
	assertEquals("nothing to say about order here", 0, this.comparator.compare(advisor1, advisor2));
}
 
Example 30
private Advisor createAspectJAdvice(int advisorOrder, int adviceDeclarationOrder, String aspectName, AbstractAspectJAdvice advice) {
	advice.setDeclarationOrder(adviceDeclarationOrder);
	advice.setAspectName(aspectName);
	AspectJPointcutAdvisor advisor = new AspectJPointcutAdvisor(advice);
	advisor.setOrder(advisorOrder);
	return advisor;
}