@Test public void testImportXmlWithNamespaceConfig() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(ImportXmlWithAopNamespaceConfig.class); Object bean = ctx.getBean("proxiedXmlBean"); assertTrue(AopUtils.isAopProxy(bean)); }
@Test public void testAutoProxyCreatorWithFactoryBeanAndProxyObjectOnly() { StaticApplicationContext sac = new StaticApplicationContext(); MutablePropertyValues pvs = new MutablePropertyValues(); pvs.add("proxyFactoryBean", "false"); sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class, pvs); sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class); sac.refresh(); TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator"); tapc.testInterceptor.nrOfInvocations = 0; FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied"); assertFalse(AopUtils.isAopProxy(factory)); TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied"); assertTrue(AopUtils.isCglibProxy(tb)); assertEquals(0, tapc.testInterceptor.nrOfInvocations); tb.getAge(); assertEquals(1, tapc.testInterceptor.nrOfInvocations); TestBean tb2 = (TestBean) sac.getBean("singletonFactoryToBeProxied"); assertSame(tb, tb2); assertEquals(1, tapc.testInterceptor.nrOfInvocations); tb2.getAge(); assertEquals(2, tapc.testInterceptor.nrOfInvocations); }
private Class<?> getTargetClass(Object targetObject) { Class<?> targetClass = targetObject.getClass(); if (AopUtils.isAopProxy(targetObject)) { targetClass = AopUtils.getTargetClass(targetObject); if (targetClass == targetObject.getClass()) { try { // Maybe a proxy with no target - e.g. gateway Class<?>[] interfaces = ((Advised) targetObject).getProxiedInterfaces(); if (interfaces != null && interfaces.length == 1) { targetClass = interfaces[0]; } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception trying to extract interface", e); } } } } else if (org.springframework.util.ClassUtils.isCglibProxyClass(targetClass)) { Class<?> superClass = targetObject.getClass().getSuperclass(); if (!Object.class.equals(superClass)) { targetClass = superClass; } } return targetClass; }
@Test public void testGetAnonymousInnerBeanFromScope() throws Exception { TestBean bean = (TestBean) this.beanFactory.getBean("outerBean"); assertFalse(AopUtils.isAopProxy(bean)); assertTrue(AopUtils.isCglibProxy(bean.getSpouse())); BeanDefinition beanDef = this.beanFactory.getBeanDefinition("outerBean"); BeanDefinitionHolder innerBeanDef = (BeanDefinitionHolder) beanDef.getPropertyValues().getPropertyValue("spouse").getValue(); String name = innerBeanDef.getBeanName(); MockHttpServletRequest request = new MockHttpServletRequest(); RequestAttributes requestAttributes = new ServletRequestAttributes(request); RequestContextHolder.setRequestAttributes(requestAttributes); try { assertNull(request.getAttribute("scopedTarget." + name)); assertEquals("scoped", bean.getSpouse().getName()); assertNotNull(request.getAttribute("scopedTarget." + name)); assertEquals(TestBean.class, request.getAttribute("scopedTarget." + name).getClass()); assertEquals("scoped", ((TestBean) request.getAttribute("scopedTarget." + name)).getName()); } finally { RequestContextHolder.setRequestAttributes(null); } }
public static Class<?> getGenericTypeFromBean(Object object) { Class<?> clazz = object.getClass(); if (AopUtils.isAopProxy(object)) { clazz = AopUtils.getTargetClass(object); } return getGenericType(clazz); }
/** * 获取目标对象. * * @param proxy 代理对象 * @return 目标对象 */ public static Object getTarget(final Object proxy) { if (!AopUtils.isAopProxy(proxy)) { return proxy; } if (AopUtils.isJdkDynamicProxy(proxy)) { return getProxyTargetObject(proxy, "h"); } else { return getProxyTargetObject(proxy, "CGLIB$CALLBACK_0"); } }
@Test public void proxyingOccurs() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(AsyncConfig.class); ctx.refresh(); AsyncBean asyncBean = ctx.getBean(AsyncBean.class); assertThat(AopUtils.isAopProxy(asyncBean), is(true)); asyncBean.work(); }
@Test public void transactionProxyIsCreated() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(EnableTxConfig.class, TxManagerConfig.class); ctx.refresh(); TransactionalTestBean bean = ctx.getBean(TransactionalTestBean.class); assertThat("testBean is not a proxy", AopUtils.isAopProxy(bean), is(true)); Map<?, ?> services = ctx.getBeansWithAnnotation(Service.class); assertThat("Stereotype annotation not visible", services.containsKey("testBean"), is(true)); }
/** * 获取 目标对象 * * @param proxy 代理对象 * @return * @throws Exception */ public static Object getTarget(Object proxy) throws Exception { if (!AopUtils.isAopProxy(proxy)) { return proxy; // 不是代理对象 } if (AopUtils.isJdkDynamicProxy(proxy)) { return getJdkDynamicProxyTargetObject(proxy); } else { // cglib return getCglibProxyTargetObject(proxy); } }
/** {@InheritDoc} */ @Override public List<BeanDetail> getBeanDetails() { if (this.allBeans == null) { // initialize BeanDetail list List<BeanDetail> beans = new ArrayList<BeanDetail>(); BeanDetail springBeanDetail; // get the list of bean names List<String> names = this.getBeanNames(); for (String beanName : names) { springBeanDetail = new BeanDetail(); springBeanDetail.setBeanName(beanName); Object bean; String beanType; springBeanDetail.setAliases(Arrays.asList(this.ctx.getAliases(beanName))); bean = this.ctx.getBean(beanName); beanType = bean.getClass().getName(); // Manage proxied beans // If the bean is proxied then its type is modiified. We // detect // it and get the correct target type if (AopUtils.isAopProxy(bean)) { beanType = AopUtils.getTargetClass(bean).getName(); springBeanDetail.setProxied(true); } springBeanDetail.setBeanType(beanType); springBeanDetail.setPrototype(this.ctx.isPrototype(beanName)); springBeanDetail.setSingleton(this.ctx.isSingleton(beanName)); springBeanDetail.setBean(this.ctx.getBean(beanName)); if (this.configurablebeanFactory != null) { BeanDefinition beanDefinition = this.configurablebeanFactory.getBeanDefinition(beanName); springBeanDetail.setBeanType(beanDefinition.getBeanClassName()); springBeanDetail.setDescription(beanDefinition.getDescription()); springBeanDetail.setScope(beanDefinition.getScope()); springBeanDetail.setLazyInit(beanDefinition.isLazyInit()); springBeanDetail.setAbstract(beanDefinition.isAbstract()); } beans.add(springBeanDetail); } this.allBeans = beans; } return this.allBeans; }
private static Object getInjectableInstance(Object o) { if (AopUtils.isAopProxy(o)) { final Advised aopResource = (Advised) o; try { return aopResource.getTargetSource().getTarget(); } catch (Exception e) { LOGGER.log(Level.SEVERE, "Could not get target object from proxy.", e); throw new RuntimeException("Could not get target object from proxy.", e); } } else { return o; } }
@Test public void succeedsWhenJdkProxyAndScheduledMethodIsPresentOnInterface() throws InterruptedException { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(Config.class, JdkProxyTxConfig.class, RepoConfigB.class); ctx.refresh(); Thread.sleep(50); // allow @Scheduled method to be called several times MyRepositoryWithScheduledMethod repository = ctx.getBean(MyRepositoryWithScheduledMethod.class); CallCountingTransactionManager txManager = ctx.getBean(CallCountingTransactionManager.class); assertThat("repository is not a proxy", AopUtils.isAopProxy(repository), is(true)); assertThat("@Scheduled method never called", repository.getInvocationCount(), greaterThan(0)); assertThat("no transactions were committed", txManager.commits, greaterThan(0)); }
@Before public void setUp() throws Exception { ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext(getClass().getSimpleName() + ".xml", getClass()); AdviceBindingTestAspect afterAdviceAspect = (AdviceBindingTestAspect) ctx.getBean("testAspect"); 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(); mockCollaborator = createNiceMock(AdviceBindingCollaborator.class); afterAdviceAspect.setCollaborator(mockCollaborator); }
@Override protected void applyReceiveOnlyAdviceChain(Collection<Advice> chain) { if (AopUtils.isAopProxy(this.source)) { for (Advice advice : chain) { NameMatchMethodPointcutAdvisor sourceAdvice = new NameMatchMethodPointcutAdvisor(advice); sourceAdvice.addMethodName("receive"); ((Advised) this.source).addAdvice(advice); } } else { ProxyFactory proxyFactory = new ProxyFactory(this.source); for (Advice advice : chain) { proxyFactory.addAdvice(advice); } this.source = (MessageSource<?>) proxyFactory.getProxy(getBeanClassLoader()); } }
@Test public void customAsyncAnnotationIsPropagated() { AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(); ctx.register(CustomAsyncAnnotationConfig.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); }
public void testNonStaticScript() throws Exception { ApplicationContext ctx = new ClassPathXmlApplicationContext("jrubyRefreshableContext.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 testInt3017DefaultConfig() throws Exception { assertSame( this.connectionFactory, TestUtils.getPropertyValue(this.defaultAdapter, "template.connectionFactory")); assertEquals( "foo", TestUtils.getPropertyValue(this.defaultAdapter, "queueNameExpression", Expression.class) .getExpressionString()); assertTrue(TestUtils.getPropertyValue(this.defaultAdapter, "extractPayload", Boolean.class)); assertFalse( TestUtils.getPropertyValue(this.defaultAdapter, "serializerExplicitlySet", Boolean.class)); Object handler = TestUtils.getPropertyValue(this.defaultEndpoint, "handler"); assertTrue(AopUtils.isAopProxy(handler)); assertSame(((Advised) handler).getTargetSource().getTarget(), this.defaultAdapter); assertThat( TestUtils.getPropertyValue(handler, "h.advised.advisors.first.item.advice"), Matchers.instanceOf(RequestHandlerRetryAdvice.class)); }
@Test public void testBeanNameAutoProxyCreatorWithFactoryBeanProxy() { StaticApplicationContext sac = new StaticApplicationContext(); sac.registerSingleton("testInterceptor", TestInterceptor.class); RootBeanDefinition proxyCreator = new RootBeanDefinition(BeanNameAutoProxyCreator.class); proxyCreator.getPropertyValues().add("interceptorNames", "testInterceptor"); proxyCreator .getPropertyValues() .add("beanNames", "singletonToBeProxied,&singletonFactoryToBeProxied"); sac.getDefaultListableBeanFactory() .registerBeanDefinition("beanNameAutoProxyCreator", proxyCreator); RootBeanDefinition bd = new RootBeanDefinition(TestBean.class); sac.getDefaultListableBeanFactory().registerBeanDefinition("singletonToBeProxied", bd); sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class); sac.refresh(); ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied"); assertTrue(Proxy.isProxyClass(singletonToBeProxied.getClass())); TestInterceptor ti = (TestInterceptor) sac.getBean("testInterceptor"); int initialNr = ti.nrOfInvocations; singletonToBeProxied.getName(); assertEquals(initialNr + 1, ti.nrOfInvocations); FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied"); assertTrue(Proxy.isProxyClass(factory.getClass())); TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied"); assertFalse(AopUtils.isAopProxy(tb)); assertEquals(initialNr + 3, ti.nrOfInvocations); tb.getAge(); assertEquals(initialNr + 3, ti.nrOfInvocations); }
@Async @Override public String facade(String orderId, int waitTime) throws Exception { logger.debug("orderService - aop proxy: {}", AopUtils.isAopProxy(orderService)); logger.debug("orderService - jdk proxy: {}", AopUtils.isJdkDynamicProxy(orderService)); logger.debug("orderService - cglib proxy: {}", AopUtils.isCglibProxy(orderService)); this.getOrderService().order(orderId); // String result = null; // Future<String> future = this.getOrderService().update(waitTime); // try { // result = future.get(); // } catch (Exception e) { // /** // * here if we don't catch the exception, the transaction of this // * 'facade()' method will be committed, as future.get() will throw a // * ExecutionException which isn't a unchecked exception. // * <p/> // * The default behaviour of transaction manager is to rollback if a // * unchecked exception(RuntimeException) thrown out. // */ // logger.error(e.getMessage()); // } // // // register a transaction event listener // TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { // private boolean committed = false; // // @Override // public void suspend() { // logger.debug("suspend()"); // } // // @Override // public void resume() { // logger.debug("resume()"); // } // // @Override // public void flush() { // logger.debug("flush()"); // } // // /** // * The order of callback methods is as below: // * <ol> // * <li>beforeCommit()</li> // * <li>beforeCompletion()</li> // * <li>afterCommit()</li> // * <li>afterCompletion()</li> // * </ol> // * If transaction will be rolled back at last, both // * <code>beforeCommit()</code> and <code>afterCommit()</code> won't // * be called. // */ // @Override // public void beforeCommit(boolean readOnly) { // logger.debug("beforeCommit()..readOnly: {}", readOnly); // } // // @Override // public void beforeCompletion() { // logger.debug("beforeCompletion()"); // } // // @Override // public void afterCommit() { // logger.debug("afterCommit()"); // this.committed = true; // } // // @Override // public void afterCompletion(int status) { // logger.debug("afterCompletion()"); // logger.debug(committed ? "committed" : "roll back"); // } // }); // // if (waitTime > 5) { // throw new RuntimeException("exception to trigger transaction rollback."); // } // return result; return null; }