Java Code Examples for org.springframework.aop.support.AopUtils

The following examples show how to use org.springframework.aop.support.AopUtils. 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: java-technology-stack   Source File: GroovyScriptFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testRefreshableFromTag() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");
	CallCounter countingAspect = (CallCounter) ctx.getBean("getMessageAspect");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals(0, countingAspect.getCalls());
	assertEquals("Hello World!", messenger.getMessage());
	assertEquals(1, countingAspect.getCalls());

	assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger));
}
 
Example 2
Source Project: dubbox-hystrix   Source File: AnnotationBean.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isMatchPackage(Object bean) {
    if (annotationPackages == null || annotationPackages.length == 0) {
        return true;
    }
    Class clazz = bean.getClass();
    if(isProxyBean(bean)){
        clazz = AopUtils.getTargetClass(bean);
    }
    String beanClassName = clazz.getName();
    for (String pkg : annotationPackages) {
        if (beanClassName.startsWith(pkg)) {
            return true;
        }
    }
    return false;
}
 
Example 3
@Test
public void testSingletonScopeIgnoresProxyInterfaces() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
	ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");

	// should not be a proxy
	assertFalse(AopUtils.isAopProxy(bean));

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// not a proxy so this should not have changed
	assertEquals(MODIFIED_NAME, bean.getName());

	// singleton bean, so name should be modified even after lookup
	ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
	assertEquals(MODIFIED_NAME, bean2.getName());
}
 
Example 4
@Test
public void testRefreshableFromTag() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovy-with-xsd.xml", getClass());
	assertTrue(Arrays.asList(ctx.getBeanNamesForType(Messenger.class)).contains("refreshableMessenger"));

	Messenger messenger = (Messenger) ctx.getBean("refreshableMessenger");
	CallCounter countingAspect = (CallCounter) ctx.getBean("getMessageAspect");

	assertTrue(AopUtils.isAopProxy(messenger));
	assertTrue(messenger instanceof Refreshable);
	assertEquals(0, countingAspect.getCalls());
	assertEquals("Hello World!", messenger.getMessage());
	assertEquals(1, countingAspect.getCalls());

	assertTrue(ctx.getBeansOfType(Messenger.class).values().contains(messenger));
}
 
Example 5
Source Project: java-technology-stack   Source File: EnableAsyncTests.java    License: MIT License 6 votes vote down vote up
@Test
public void customAsyncAnnotationIsPropagated() {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(CustomAsyncAnnotationConfig.class, CustomAsyncBean.class);
	ctx.refresh();

	Object bean = ctx.getBean(CustomAsyncBean.class);
	assertTrue(AopUtils.isAopProxy(bean));
	boolean isAsyncAdvised = false;
	for (Advisor advisor : ((Advised) bean).getAdvisors()) {
		if (advisor instanceof AsyncAnnotationAdvisor) {
			isAsyncAdvised = true;
			break;
		}
	}
	assertTrue("bean was not async advised as expected", isAsyncAdvised);

	ctx.close();
}
 
Example 6
Source Project: spring-analysis-note   Source File: BeforeAdviceBindingTests.java    License: MIT License 6 votes vote down vote up
@Before
public void setup() throws Exception {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	testBeanTarget = (TestBean) ((Advised) testBeanProxy).getTargetSource().getTarget();

	AdviceBindingTestAspect beforeAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AdviceBindingCollaborator.class);
	beforeAdviceAspect.setCollaborator(mockCollaborator);
}
 
Example 7
Source Project: java-technology-stack   Source File: BshScriptFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void nonStaticPrototypeScript() {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("bshRefreshableContext.xml", getClass());
	ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype");
	ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype");

	assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger));
	assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable);

	assertEquals("Hello World!", messenger.getMessage());
	assertEquals("Hello World!", messenger2.getMessage());
	messenger.setMessage("Bye World!");
	messenger2.setMessage("Byebye World!");
	assertEquals("Bye World!", messenger.getMessage());
	assertEquals("Byebye World!", messenger2.getMessage());

	Refreshable refreshable = (Refreshable) messenger;
	refreshable.refresh();

	assertEquals("Hello World!", messenger.getMessage());
	assertEquals("Byebye World!", messenger2.getMessage());
	assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount());
}
 
Example 8
Source Project: spring4-understanding   Source File: BenchmarkTests.java    License: Apache License 2.0 6 votes vote down vote up
private long testAfterReturningAdviceWithoutJoinPoint(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	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();
}
 
Example 9
@Test
public void testStaticPrototypeScript() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyContext.xml", getClass());
	ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype");
	ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype");

	assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger));
	assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable);

	assertNotSame(messenger, messenger2);
	assertSame(messenger.getClass(), messenger2.getClass());
	assertEquals("Hello World!", messenger.getMessage());
	assertEquals("Hello World!", messenger2.getMessage());
	messenger.setMessage("Bye World!");
	messenger2.setMessage("Byebye World!");
	assertEquals("Bye World!", messenger.getMessage());
	assertEquals("Byebye World!", messenger2.getMessage());
}
 
Example 10
@Test
public void testDestructionAtRequestCompletion() throws Exception {
	String name = "requestScopedDisposableObject";
	DerivedTestBean bean = (DerivedTestBean) this.beanFactory.getBean(name);
	assertTrue(AopUtils.isCglibProxy(bean));

	MockHttpServletRequest request = new MockHttpServletRequest();
	ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		assertNull(request.getAttribute("scopedTarget." + name));
		assertEquals("scoped", bean.getName());
		assertNotNull(request.getAttribute("scopedTarget." + name));
		assertEquals(DerivedTestBean.class, request.getAttribute("scopedTarget." + name).getClass());
		assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName());
		assertSame(bean, this.beanFactory.getBean(name));

		requestAttributes.requestCompleted();
		assertTrue(((TestBean) request.getAttribute("scopedTarget." + name)).wasDestroyed());
	}
	finally {
		RequestContextHolder.setRequestAttributes(null);
	}
}
 
Example 11
@Test
public void testSingletonScopeIgnoresProxyInterfaces() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
	ScopedTestBean bean = (ScopedTestBean) context.getBean("singleton");

	// should not be a proxy
	assertFalse(AopUtils.isAopProxy(bean));

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// not a proxy so this should not have changed
	assertEquals(MODIFIED_NAME, bean.getName());

	// singleton bean, so name should be modified even after lookup
	ScopedTestBean bean2 = (ScopedTestBean) context.getBean("singleton");
	assertEquals(MODIFIED_NAME, bean2.getName());
}
 
Example 12
Source Project: spring4-understanding   Source File: ProxyFactoryTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testProxyTargetClassWithConcreteClassAsTarget() {
	ProxyFactory pf = new ProxyFactory();
	pf.setTargetClass(TestBean.class);
	Object proxy = pf.getProxy();
	assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy));
	assertTrue(proxy instanceof TestBean);
	assertEquals(TestBean.class, AopProxyUtils.ultimateTargetClass(proxy));

	ProxyFactory pf2 = new ProxyFactory(proxy);
	pf2.setProxyTargetClass(true);
	Object proxy2 = pf2.getProxy();
	assertTrue("Proxy is a CGLIB proxy", AopUtils.isCglibProxy(proxy2));
	assertTrue(proxy2 instanceof TestBean);
	assertEquals(TestBean.class, AopProxyUtils.ultimateTargetClass(proxy2));
}
 
Example 13
Source Project: spring4-understanding   Source File: BenchmarkTests.java    License: Apache License 2.0 6 votes vote down vote up
private long testRepeatedAroundAdviceInvocations(String file, int howmany, String technology) {
	ClassPathXmlApplicationContext bf = new ClassPathXmlApplicationContext(file, CLASS);

	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();
}
 
Example 14
Source Project: es   Source File: AopProxyUtils.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean hasAdvice(Object proxy, Class<? extends Advice> adviceClass) {
    if(!AopUtils.isAopProxy(proxy)) {
        return false;
    }
    ProxyFactory proxyFactory = null;
    if(AopUtils.isJdkDynamicProxy(proxy)) {
        proxyFactory = findJdkDynamicProxyFactory(proxy);
    }
    if(AopUtils.isCglibProxy(proxy)) {
        proxyFactory = findCglibProxyFactory(proxy);
    }

    Advisor[] advisors = proxyFactory.getAdvisors();

    if(advisors == null || advisors.length == 0) {
        return false;
    }

    for(Advisor advisor : advisors) {
        if(adviceClass.isAssignableFrom(advisor.getAdvice().getClass())) {
            return true;
        }
    }
    return false;
}
 
Example 15
Source Project: java-technology-stack   Source File: GroovyScriptFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testNonStaticScript() throws Exception {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("groovyRefreshableContext.xml", getClass());
	Messenger messenger = (Messenger) ctx.getBean("messenger");

	assertTrue("Should be a proxy for refreshable scripts", AopUtils.isAopProxy(messenger));
	assertTrue("Should be an instance of Refreshable", messenger instanceof Refreshable);

	String desiredMessage = "Hello World!";
	assertEquals("Message is incorrect", desiredMessage, messenger.getMessage());

	Refreshable refreshable = (Refreshable) messenger;
	refreshable.refresh();

	assertEquals("Message is incorrect after refresh.", desiredMessage, messenger.getMessage());
	assertEquals("Incorrect refresh count", 2, refreshable.getRefreshCount());
}
 
Example 16
Source Project: java-technology-stack   Source File: RequestScopedProxyTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetFromScope() throws Exception {
	String name = "requestScopedObject";
	TestBean bean = (TestBean) this.beanFactory.getBean(name);
	assertTrue(AopUtils.isCglibProxy(bean));

	MockHttpServletRequest request = new MockHttpServletRequest();
	RequestAttributes requestAttributes = new ServletRequestAttributes(request);
	RequestContextHolder.setRequestAttributes(requestAttributes);

	try {
		assertNull(request.getAttribute("scopedTarget." + name));
		assertEquals("scoped", bean.getName());
		assertNotNull(request.getAttribute("scopedTarget." + name));
		TestBean target = (TestBean) request.getAttribute("scopedTarget." + name);
		assertEquals(TestBean.class, target.getClass());
		assertEquals("scoped", target.getName());
		assertSame(bean, this.beanFactory.getBean(name));
		assertEquals(bean.toString(), target.toString());
	}
	finally {
		RequestContextHolder.setRequestAttributes(null);
	}
}
 
Example 17
@Before
public void setup() throws Exception {
	ClassPathXmlApplicationContext ctx =
			new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass());

	afterAdviceAspect = (AfterReturningAdviceBindingTestAspect) ctx.getBean("testAspect");

	mockCollaborator = mock(AfterReturningAdviceBindingCollaborator.class);
	afterAdviceAspect.setCollaborator(mockCollaborator);

	testBeanProxy = (ITestBean) ctx.getBean("testBean");
	assertTrue(AopUtils.isAopProxy(testBeanProxy));

	// we need the real target too, not just the proxy...
	this.testBeanTarget = (TestBean) ((Advised)testBeanProxy).getTargetSource().getTarget();
}
 
Example 18
@Test
public void testRequestScopeWithProxiedInterfaces() {
	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	ApplicationContext context = createContext(ScopedProxyMode.INTERFACES);
	IScopedTestBean bean = (IScopedTestBean) context.getBean("request");

	// should be dynamic proxy, implementing both interfaces
	assertTrue(AopUtils.isJdkDynamicProxy(bean));
	assertTrue(bean instanceof AnotherScopeTestInterface);

	assertEquals(DEFAULT_NAME, bean.getName());
	bean.setName(MODIFIED_NAME);

	RequestContextHolder.setRequestAttributes(newRequestAttributes);
	// this is a proxy so it should be reset to default
	assertEquals(DEFAULT_NAME, bean.getName());

	RequestContextHolder.setRequestAttributes(oldRequestAttributes);
	assertEquals(MODIFIED_NAME, bean.getName());
}
 
Example 19
@Test
public void eventListenerWorksWithCglibProxy() throws Exception {
	load(CglibProxyTestBean.class);

	CglibProxyTestBean proxy = this.context.getBean(CglibProxyTestBean.class);
	assertTrue("bean should be a cglib proxy", AopUtils.isCglibProxy(proxy));
	this.eventCollector.assertNoEventReceived(proxy.getId());

	this.context.publishEvent(new ContextRefreshedEvent(this.context));
	this.eventCollector.assertNoEventReceived(proxy.getId());

	TestEvent event = new TestEvent();
	this.context.publishEvent(event);
	this.eventCollector.assertEvent(proxy.getId(), event);
	this.eventCollector.assertTotalEventsCount(1);
}
 
Example 20
@SuppressWarnings("rawtypes")
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
	Class<?> targetClass = AopUtils.getTargetClass(bean);
	if (targetClass == null) {
		return bean;
	}

	Compensable compensable = targetClass.getAnnotation(Compensable.class);
	if (compensable == null) {
		return bean;
	}

	Field[] fields = targetClass.getDeclaredFields();
	for (int i = 0; fields != null && i < fields.length; i++) {
		Field field = fields[i];
		Reference reference = field.getAnnotation(Reference.class);
		if (reference == null) {
			continue;
		}

		ReferenceBean referenceConfig = new ReferenceBean(reference);
		this.validateReferenceBean(beanName, referenceConfig);
	}

	return bean;
}
 
Example 21
@Test
public void genericsBasedInjectionWithLateGenericsMatchingOnJdkProxyAndRawInstance() {
	beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(RawInstanceRepositoryConfiguration.class));
	new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory);
	DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
	autoProxyCreator.setBeanFactory(beanFactory);
	beanFactory.addBeanPostProcessor(autoProxyCreator);
	beanFactory.registerSingleton("traceInterceptor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor()));
	beanFactory.preInstantiateSingletons();

	String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class);
	assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo"));

	beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class));
	assertEquals(1, beanNames.length);
	assertEquals("stringRepo", beanNames[0]);

	beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class));
	assertEquals(1, beanNames.length);
	assertEquals("stringRepo", beanNames[0]);

	assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo")));
}
 
Example 22
Source Project: java-technology-stack   Source File: CglibProxyTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testProxyCanBeClassNotInterface() {
	TestBean raw = new TestBean();
	raw.setAge(32);
	mockTargetSource.setTarget(raw);
	AdvisedSupport pc = new AdvisedSupport();
	pc.setTargetSource(mockTargetSource);
	AopProxy aop = new CglibAopProxy(pc);

	Object proxy = aop.getProxy();
	assertTrue(AopUtils.isCglibProxy(proxy));
	assertTrue(proxy instanceof ITestBean);
	assertTrue(proxy instanceof TestBean);

	TestBean tb = (TestBean) proxy;
	assertEquals(32, tb.getAge());
}
 
Example 23
protected void doTestAspectsAndAdvisorAreApplied(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);
}
 
Example 24
@Test
public void withScopedProxy() throws IOException, ClassNotFoundException {
	AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	ctx.register(ComponentScanWithScopedProxy.class);
	ctx.getBeanFactory().registerScope("myScope", new SimpleMapScope());
	ctx.refresh();
	// should cast to the interface
	FooService bean = (FooService) ctx.getBean("scopedProxyTestBean");
	// should be dynamic proxy
	assertThat(AopUtils.isJdkDynamicProxy(bean), is(true));
	// test serializability
	assertThat(bean.foo(1), equalTo("bar"));
	FooService deserialized = (FooService) SerializationTestUtils.serializeAndDeserialize(bean);
	assertThat(deserialized, notNullValue());
	assertThat(deserialized.foo(1), equalTo("bar"));
}
 
Example 25
Source Project: spring-analysis-note   Source File: BshScriptFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void staticPrototypeScript() {
	ApplicationContext ctx = new ClassPathXmlApplicationContext("bshContext.xml", getClass());
	ConfigurableMessenger messenger = (ConfigurableMessenger) ctx.getBean("messengerPrototype");
	ConfigurableMessenger messenger2 = (ConfigurableMessenger) ctx.getBean("messengerPrototype");

	assertFalse("Shouldn't get proxy when refresh is disabled", AopUtils.isAopProxy(messenger));
	assertFalse("Scripted object should not be instance of Refreshable", messenger instanceof Refreshable);

	assertNotSame(messenger, messenger2);
	assertSame(messenger.getClass(), messenger2.getClass());
	assertEquals("Hello World!", messenger.getMessage());
	assertEquals("Hello World!", messenger2.getMessage());
	messenger.setMessage("Bye World!");
	messenger2.setMessage("Byebye World!");
	assertEquals("Bye World!", messenger.getMessage());
	assertEquals("Byebye World!", messenger2.getMessage());
}
 
Example 26
Source Project: vaadin4spring   Source File: ScopedEventBus.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param scope          the scope of the events that this event bus handles.
 * @param parentEventBus the parent event bus to use, may be {@code null};
 */
public ScopedEventBus(EventScope scope, EventBus parentEventBus) {
    eventScope = scope;
    this.parentEventBus = parentEventBus;
    if (parentEventBus != null) {
        if (AopUtils.isJdkDynamicProxy(parentEventBus)) {
            logger.debug("Parent event bus [{}] is proxied, trying to get the real EventBus instance",
                    parentEventBus);
            try {
                this.parentEventBus = (EventBus) ((Advised) parentEventBus).getTargetSource().getTarget();
            } catch (Exception e) {
                logger.error("Could not get target EventBus from proxy", e);
                throw new RuntimeException("Could not get parent event bus", e);
            }
        }
        logger.debug("Using parent event bus [{}]", this.parentEventBus);
        this.parentEventBus.subscribe(parentListener);
    }
}
 
Example 27
@Test
public void genericsBasedInjectionWithEarlyGenericsMatchingOnJdkProxy() {
	beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(RepositoryConfiguration.class));
	new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory);
	DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
	autoProxyCreator.setBeanFactory(beanFactory);
	beanFactory.addBeanPostProcessor(autoProxyCreator);
	beanFactory.registerSingleton("traceInterceptor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor()));

	String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class);
	assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo"));

	beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class));
	assertEquals(1, beanNames.length);
	assertEquals("stringRepo", beanNames[0]);

	beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class));
	assertEquals(1, beanNames.length);
	assertEquals("stringRepo", beanNames[0]);

	assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo")));
}
 
Example 28
/**
 * Check that we can provide a common interceptor that will
 * appear in the chain before "specific" interceptors,
 * which are sourced from matching advisors
 */
@Test
public void testCommonInterceptorAndAdvisor() throws Exception {
	BeanFactory bf = new ClassPathXmlApplicationContext(COMMON_INTERCEPTORS_CONTEXT, CLASS);
	ITestBean test1 = (ITestBean) bf.getBean("test1");
	assertTrue(AopUtils.isAopProxy(test1));

	Lockable lockable1 = (Lockable) test1;
	NopInterceptor nop = (NopInterceptor) bf.getBean("nopInterceptor");
	assertEquals(0, nop.getCount());

	ITestBean test2 = (ITestBean) bf.getBean("test2");
	Lockable lockable2 = (Lockable) test2;

	// Locking should be independent; nop is shared
	assertFalse(lockable1.locked());
	assertFalse(lockable2.locked());
	// equals 2 calls on shared nop, because it's first
	// and sees calls against the Lockable interface introduced
	// by the specific advisor
	assertEquals(2, nop.getCount());
	lockable1.lock();
	assertTrue(lockable1.locked());
	assertFalse(lockable2.locked());
	assertEquals(5, nop.getCount());
}
 
Example 29
@Test
public void genericsBasedInjectionWithLateGenericsMatchingOnJdkProxy() {
	beanFactory.registerBeanDefinition("configClass", new RootBeanDefinition(RepositoryConfiguration.class));
	new ConfigurationClassPostProcessor().postProcessBeanFactory(beanFactory);
	DefaultAdvisorAutoProxyCreator autoProxyCreator = new DefaultAdvisorAutoProxyCreator();
	autoProxyCreator.setBeanFactory(beanFactory);
	beanFactory.addBeanPostProcessor(autoProxyCreator);
	beanFactory.registerSingleton("traceInterceptor", new DefaultPointcutAdvisor(new SimpleTraceInterceptor()));
	beanFactory.preInstantiateSingletons();

	String[] beanNames = beanFactory.getBeanNamesForType(RepositoryInterface.class);
	assertTrue(ObjectUtils.containsElement(beanNames, "stringRepo"));

	beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class));
	assertEquals(1, beanNames.length);
	assertEquals("stringRepo", beanNames[0]);

	beanNames = beanFactory.getBeanNamesForType(ResolvableType.forClassWithGenerics(RepositoryInterface.class, String.class));
	assertEquals(1, beanNames.length);
	assertEquals("stringRepo", beanNames[0]);

	assertTrue(AopUtils.isJdkDynamicProxy(beanFactory.getBean("stringRepo")));
}
 
Example 30
Source Project: attic-rave   Source File: SynchronizingAspect.java    License: Apache License 2.0 5 votes vote down vote up
private Method getTargetMethod(Class<?> targetClass, Method method) {
    Method targetMethod = targetMethodCache.get(method);
    if (targetMethod == null) {
        targetMethod = AopUtils.getMostSpecificMethod(method, targetClass);
        targetMethodCache.put(method, targetMethod);
    }
    return targetMethod;
}