コード例 #1
0
  @Test
  public void testCustomAutoProxyCreator() {
    StaticApplicationContext sac = new StaticApplicationContext();
    sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);
    sac.registerSingleton("singletonNoInterceptor", TestBean.class);
    sac.registerSingleton("singletonToBeProxied", TestBean.class);
    sac.registerPrototype("prototypeToBeProxied", TestBean.class);
    sac.refresh();

    MessageSource messageSource = (MessageSource) sac.getBean("messageSource");
    ITestBean singletonNoInterceptor = (ITestBean) sac.getBean("singletonNoInterceptor");
    ITestBean singletonToBeProxied = (ITestBean) sac.getBean("singletonToBeProxied");
    ITestBean prototypeToBeProxied = (ITestBean) sac.getBean("prototypeToBeProxied");
    assertFalse(AopUtils.isCglibProxy(messageSource));
    assertTrue(AopUtils.isCglibProxy(singletonNoInterceptor));
    assertTrue(AopUtils.isCglibProxy(singletonToBeProxied));
    assertTrue(AopUtils.isCglibProxy(prototypeToBeProxied));

    TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
    assertEquals(0, tapc.testInterceptor.nrOfInvocations);
    singletonNoInterceptor.getName();
    assertEquals(0, tapc.testInterceptor.nrOfInvocations);
    singletonToBeProxied.getAge();
    assertEquals(1, tapc.testInterceptor.nrOfInvocations);
    prototypeToBeProxied.getSpouse();
    assertEquals(2, tapc.testInterceptor.nrOfInvocations);
  }
コード例 #2
0
  @Test
  public void testAutoProxyCreatorWithFactoryBeanAndProxyFactoryBeanOnly() {
    StaticApplicationContext sac = new StaticApplicationContext();

    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.add("proxyObject", "false");
    sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class, pvs);

    pvs = new MutablePropertyValues();
    pvs.add("singleton", "false");
    sac.registerSingleton("prototypeFactoryToBeProxied", DummyFactory.class, pvs);

    sac.refresh();

    TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
    tapc.testInterceptor.nrOfInvocations = 0;

    FactoryBean<?> prototypeFactory = (FactoryBean<?>) sac.getBean("&prototypeFactoryToBeProxied");
    assertTrue(AopUtils.isCglibProxy(prototypeFactory));
    TestBean tb = (TestBean) sac.getBean("prototypeFactoryToBeProxied");
    assertFalse(AopUtils.isCglibProxy(tb));

    assertEquals(2, tapc.testInterceptor.nrOfInvocations);
    tb.getAge();
    assertEquals(2, tapc.testInterceptor.nrOfInvocations);
  }
コード例 #3
0
  @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);
    }
  }
コード例 #4
0
  @Test
  public void withCglibProxy() {
    ApplicationContext ctx = new AnnotationConfigApplicationContext(ConfigWithCglibProxy.class);

    aspectIsApplied(ctx);
    assertThat(AopUtils.isCglibProxy(ctx.getBean(FooService.class)), is(true));
  }
コード例 #5
0
 private Map<String, Object> getHandlerMap(AbstractUrlHandlerMapping mapping) {
   if (AopUtils.isCglibProxy(mapping)) {
     // If the AbstractUrlHandlerMapping is a cglib proxy we can't call
     // the final getHandlerMap() method.
     return Collections.emptyMap();
   }
   return mapping.getHandlerMap();
 }
コード例 #6
0
 @Test
 public void annotatedService_PTC_true() {
   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
   ctx.register(PTCTrue.class, NonAnnotatedServiceImpl.class);
   ctx.refresh();
   AnnotatedService s = ctx.getBean(AnnotatedService.class);
   assertTrue("expected a subclass proxy", AopUtils.isCglibProxy(s));
   assertThat(s, instanceOf(NonAnnotatedServiceImpl.class));
 }
コード例 #7
0
  @Test
  public void testAutoProxyCreatorWithFactoryBean() {
    StaticApplicationContext sac = new StaticApplicationContext();
    sac.registerSingleton("testAutoProxyCreator", TestAutoProxyCreator.class);
    sac.registerSingleton("singletonFactoryToBeProxied", DummyFactory.class);
    sac.refresh();

    TestAutoProxyCreator tapc = (TestAutoProxyCreator) sac.getBean("testAutoProxyCreator");
    tapc.testInterceptor.nrOfInvocations = 0;

    FactoryBean<?> factory = (FactoryBean<?>) sac.getBean("&singletonFactoryToBeProxied");
    assertTrue(AopUtils.isCglibProxy(factory));

    TestBean tb = (TestBean) sac.getBean("singletonFactoryToBeProxied");
    assertTrue(AopUtils.isCglibProxy(tb));
    assertEquals(2, tapc.testInterceptor.nrOfInvocations);
    tb.getAge();
    assertEquals(3, tapc.testInterceptor.nrOfInvocations);
  }
コード例 #8
0
 @SuppressWarnings("rawtypes")
 public synchronized void unbindDescriptor(WorkflowDescriptor descriptor, Map properties) {
   if (AopUtils.isCglibProxy(descriptor)) {
     try {
       descriptor = (WorkflowDescriptor) findSpringTargetSource(descriptor);
     } catch (Exception e) {
       LOG.debug("Can't extract target object from proxied one", e);
     }
   }
   workflowDescriptors.remove(descriptor);
 }
  @Test
  public void testCglibTransactionProxyImplementsNoInterfaces() throws NoSuchMethodException {
    ImplementsNoInterfaces ini = (ImplementsNoInterfaces) factory.getBean("cglibNoInterfaces");
    assertTrue("testBean is CGLIB advised", AopUtils.isCglibProxy(ini));
    String newName = "Gordon";

    // Install facade
    CallCountingTransactionManager ptm = new CallCountingTransactionManager();
    PlatformTransactionManagerFacade.delegate = ptm;

    ini.setName(newName);
    assertEquals(newName, ini.getName());
    assertEquals(2, ptm.commits);
  }
コード例 #10
0
 protected Object loadObjectWithBundleClassloader(String className) {
   Object ret = null;
   if (className != null) {
     synchronized (this) {
       for (WorkflowDescriptor descriptor : workflowDescriptors) {
         if (AopUtils.isCglibProxy(descriptor)) {
           try {
             descriptor = (WorkflowDescriptor) findSpringTargetSource(descriptor);
           } catch (Exception e) {
             LOG.debug("Can't extract target object from proxied one", e);
           }
         }
         ret = loadObject(className, descriptor.getClass().getClassLoader(), false);
         if (ret != null) break;
       }
     }
   }
   return ret;
 }
コード例 #11
0
 private void doTestWithMultipleTransactionManagers(ApplicationContext context) {
   CallCountingTransactionManager tm1 =
       context.getBean("transactionManager1", CallCountingTransactionManager.class);
   CallCountingTransactionManager tm2 =
       context.getBean("transactionManager2", CallCountingTransactionManager.class);
   TransactionalService service = context.getBean("service", TransactionalService.class);
   assertTrue(AopUtils.isCglibProxy(service));
   service.setSomething("someName");
   assertEquals(1, tm1.commits);
   assertEquals(0, tm2.commits);
   service.doSomething();
   assertEquals(1, tm1.commits);
   assertEquals(1, tm2.commits);
   service.setSomething("someName");
   assertEquals(2, tm1.commits);
   assertEquals(1, tm2.commits);
   service.doSomething();
   assertEquals(2, tm1.commits);
   assertEquals(2, tm2.commits);
 }
コード例 #12
0
  @Test
  public void testGetFromFactoryBeanInScope() throws Exception {
    String name = "requestScopedFactoryBean";
    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(DummyFactory.SINGLETON_NAME, bean.getName());
      assertNotNull(request.getAttribute("scopedTarget." + name));
      assertEquals(DummyFactory.class, request.getAttribute("scopedTarget." + name).getClass());
      assertSame(bean, this.beanFactory.getBean(name));
    } finally {
      RequestContextHolder.setRequestAttributes(null);
    }
  }
コード例 #13
0
  @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);
    }
  }
コード例 #14
0
  @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 testGetsAreNotTransactionalWithProxyFactory2Cglib() throws NoSuchMethodException {
   ITestBean testBean = (ITestBean) factory.getBean("proxyFactory2Cglib");
   assertTrue("testBean is CGLIB advised", AopUtils.isCglibProxy(testBean));
   doTestGetsAreNotTransactional(testBean);
 }
コード例 #16
0
  @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;
  }
コード例 #17
0
  protected void processScheduled(Scheduled scheduled, Method method, Object bean) {
    try {
      Assert.isTrue(
          void.class.equals(method.getReturnType()),
          "Only void-returning methods may be annotated with @Scheduled");
      Assert.isTrue(
          method.getParameterTypes().length == 0,
          "Only no-arg methods may be annotated with @Scheduled");

      if (AopUtils.isJdkDynamicProxy(bean)) {
        try {
          // Found a @Scheduled method on the target class for this JDK proxy ->
          // is it also present on the proxy itself?
          method = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
        } catch (SecurityException ex) {
          ReflectionUtils.handleReflectionException(ex);
        } catch (NoSuchMethodException ex) {
          throw new IllegalStateException(
              String.format(
                  "@Scheduled method '%s' found on bean target class '%s' but not "
                      + "found in any interface(s) for a dynamic proxy. Either pull the "
                      + "method up to a declared interface or switch to subclass (CGLIB) "
                      + "proxies by setting proxy-target-class/proxyTargetClass to 'true'",
                  method.getName(), method.getDeclaringClass().getSimpleName()));
        }
      } else if (AopUtils.isCglibProxy(bean)) {
        // Common problem: private methods end up in the proxy instance, not getting delegated.
        if (Modifier.isPrivate(method.getModifiers())) {
          LogFactory.getLog(ScheduledAnnotationBeanPostProcessor.class)
              .warn(
                  String.format(
                      "@Scheduled method '%s' found on CGLIB proxy for target class '%s' but cannot "
                          + "be delegated to target bean. Switch its visibility to package or protected.",
                      method.getName(), method.getDeclaringClass().getSimpleName()));
        }
      }

      Runnable runnable = new ScheduledMethodRunnable(bean, method);
      boolean processedSchedule = false;
      String errorMessage =
          "Exactly one of the 'cron', 'fixedDelay(String)', or 'fixedRate(String)' attributes is required";

      // Determine initial delay
      long initialDelay = scheduled.initialDelay();
      String initialDelayString = scheduled.initialDelayString();
      if (StringUtils.hasText(initialDelayString)) {
        Assert.isTrue(initialDelay < 0, "Specify 'initialDelay' or 'initialDelayString', not both");
        if (this.embeddedValueResolver != null) {
          initialDelayString = this.embeddedValueResolver.resolveStringValue(initialDelayString);
        }
        try {
          initialDelay = Integer.parseInt(initialDelayString);
        } catch (NumberFormatException ex) {
          throw new IllegalArgumentException(
              "Invalid initialDelayString value \""
                  + initialDelayString
                  + "\" - cannot parse into integer");
        }
      }

      // Check cron expression
      String cron = scheduled.cron();
      if (StringUtils.hasText(cron)) {
        Assert.isTrue(initialDelay == -1, "'initialDelay' not supported for cron triggers");
        processedSchedule = true;
        String zone = scheduled.zone();
        if (this.embeddedValueResolver != null) {
          cron = this.embeddedValueResolver.resolveStringValue(cron);
          zone = this.embeddedValueResolver.resolveStringValue(zone);
        }
        TimeZone timeZone;
        if (StringUtils.hasText(zone)) {
          timeZone = StringUtils.parseTimeZoneString(zone);
        } else {
          timeZone = TimeZone.getDefault();
        }
        this.registrar.addCronTask(new CronTask(runnable, new CronTrigger(cron, timeZone)));
      }

      // At this point we don't need to differentiate between initial delay set or not anymore
      if (initialDelay < 0) {
        initialDelay = 0;
      }

      // Check fixed delay
      long fixedDelay = scheduled.fixedDelay();
      if (fixedDelay >= 0) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        this.registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
      }
      String fixedDelayString = scheduled.fixedDelayString();
      if (StringUtils.hasText(fixedDelayString)) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        if (this.embeddedValueResolver != null) {
          fixedDelayString = this.embeddedValueResolver.resolveStringValue(fixedDelayString);
        }
        try {
          fixedDelay = Integer.parseInt(fixedDelayString);
        } catch (NumberFormatException ex) {
          throw new IllegalArgumentException(
              "Invalid fixedDelayString value \""
                  + fixedDelayString
                  + "\" - cannot parse into integer");
        }
        this.registrar.addFixedDelayTask(new IntervalTask(runnable, fixedDelay, initialDelay));
      }

      // Check fixed rate
      long fixedRate = scheduled.fixedRate();
      if (fixedRate >= 0) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
      }
      String fixedRateString = scheduled.fixedRateString();
      if (StringUtils.hasText(fixedRateString)) {
        Assert.isTrue(!processedSchedule, errorMessage);
        processedSchedule = true;
        if (this.embeddedValueResolver != null) {
          fixedRateString = this.embeddedValueResolver.resolveStringValue(fixedRateString);
        }
        try {
          fixedRate = Integer.parseInt(fixedRateString);
        } catch (NumberFormatException ex) {
          throw new IllegalArgumentException(
              "Invalid fixedRateString value \""
                  + fixedRateString
                  + "\" - cannot parse into integer");
        }
        this.registrar.addFixedRateTask(new IntervalTask(runnable, fixedRate, initialDelay));
      }

      // Check whether we had any attribute set
      Assert.isTrue(processedSchedule, errorMessage);
    } catch (IllegalArgumentException ex) {
      throw new IllegalStateException(
          "Encountered invalid @Scheduled method '" + method.getName() + "': " + ex.getMessage());
    }
  }