org.springframework.context.annotation4.FactoryMethodComponent#org.springframework.aop.support.AopUtils源码实例Demo

下面列出了org.springframework.context.annotation4.FactoryMethodComponent#org.springframework.aop.support.AopUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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));
}
 
源代码2 项目: dubbox-hystrix   文件: AnnotationBean.java
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;
}
 
@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());
}
 
@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));
}
 
源代码5 项目: java-technology-stack   文件: EnableAsyncTests.java
@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();
}
 
@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);
}
 
@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());
}
 
源代码8 项目: spring4-understanding   文件: BenchmarkTests.java
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();
}
 
@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());
}
 
@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);
	}
}
 
@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());
}
 
源代码12 项目: spring4-understanding   文件: ProxyFactoryTests.java
@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));
}
 
源代码13 项目: spring4-understanding   文件: BenchmarkTests.java
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();
}
 
源代码14 项目: es   文件: AopProxyUtils.java
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;
}
 
@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());
}
 
@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);
	}
}
 
@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();
}
 
@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());
}
 
@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);
}
 
源代码20 项目: ByteTCC   文件: CompensableBeanConfigValidator.java
@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;
}
 
@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")));
}
 
源代码22 项目: java-technology-stack   文件: CglibProxyTests.java
@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());
}
 
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);
}
 
@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"));
}
 
@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());
}
 
源代码26 项目: vaadin4spring   文件: ScopedEventBus.java
/**
 * @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);
    }
}
 
@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")));
}
 
/**
 * 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());
}
 
@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")));
}
 
源代码30 项目: attic-rave   文件: SynchronizingAspect.java
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;
}