org.springframework.aop.support.AopUtils Java Examples

The following examples show how to use org.springframework.aop.support.AopUtils. 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 File: AnnotationDrivenEventListenerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #2
Source File: GroovyScriptFactoryTests.java    From java-technology-stack with 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 #3
Source File: ClassPathBeanDefinitionScannerJsr330ScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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
Source File: AdvisorAutoProxyCreatorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 #5
Source File: AnnotationBean.java    From dubbox-hystrix with 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 #6
Source File: GroovyScriptFactoryTests.java    From spring4-understanding with Apache License 2.0 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 #7
Source File: ConfigurationClassPostProcessorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #8
Source File: GroovyScriptFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #9
Source File: BeforeAdviceBindingTests.java    From spring-analysis-note with 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 #10
Source File: BshScriptFactoryTests.java    From java-technology-stack with 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 #11
Source File: BenchmarkTests.java    From spring4-understanding with 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 #12
Source File: EnableAsyncTests.java    From java-technology-stack with 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 #13
Source File: ConfigurationClassPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #14
Source File: RequestScopedProxyTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #15
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #16
Source File: BenchmarkTests.java    From spring4-understanding with 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 #17
Source File: AopProxyUtils.java    From es with 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 #18
Source File: ScopedEventBus.java    From vaadin4spring with 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 #19
Source File: BshScriptFactoryTests.java    From spring-analysis-note with 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 #20
Source File: ComponentScanAnnotationIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #21
Source File: GroovyScriptFactoryTests.java    From java-technology-stack with 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 #22
Source File: AspectJAutoProxyCreatorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
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 #23
Source File: CglibProxyTests.java    From java-technology-stack with 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 #24
Source File: ConfigurationClassPostProcessorTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #25
Source File: RequestScopedProxyTests.java    From java-technology-stack with 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 #26
Source File: AfterReturningAdviceBindingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #27
Source File: ClassPathBeanDefinitionScannerScopeIntegrationTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #28
Source File: CompensableBeanConfigValidator.java    From ByteTCC with GNU Lesser General Public License v3.0 6 votes vote down vote up
@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 #29
Source File: ProxyFactoryTests.java    From spring4-understanding with 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 #30
Source File: DtsTransactionScaner.java    From dts with Apache License 2.0 5 votes vote down vote up
@Override
protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
    try {
        synchronized (proxyedSet) {
            if (proxyedSet.contains(beanName)) {
                return bean;
            }
            proxyedSet.add(beanName);
            Class<?> serviceInterface = findTargetClass(bean);
            Method[] methods = serviceInterface.getMethods();
            LinkedList<MethodDesc> methodDescList = new LinkedList<MethodDesc>();
            for (Method method : methods) {
                DtsTransaction anno = method.getAnnotation(DtsTransaction.class);
                if (anno != null) {
                    methodDescList.add(makeMethodDesc(anno, method));
                }
            }
            if (methodDescList.size() != 0) {
                interceptor = new TransactionDtsInterceptor(methodDescList);
            } else {
                return bean;
            }
            if (!AopUtils.isAopProxy(bean)) {
                bean = super.wrapIfNecessary(bean, beanName, cacheKey);
            } else {
                AdvisedSupport advised = getAdvisedSupport(bean);
                Advisor[] advisor = buildAdvisors(beanName, getAdvicesAndAdvisorsForBean(null, null, null));
                for (Advisor avr : advisor) {
                    advised.addAdvisor(0, avr);
                }
            }
            return bean;
        }
    } catch (Exception e) {
        throw new DtsException(e);
    }
}