@Test
  public void logBeansInContext() {
    DefaultListableBeanFactory factory = (DefaultListableBeanFactory) beanFactory;
    if (factory != null) {
      logger.debug("Bean Factory: '{}'", factory);
    }

    if (applicationContext.getParent() != null) {
      logger.debug("Bean Factory: '{}'", applicationContext.getParentBeanFactory());
    }
    logger.debug("******************************************************************************");
    String[] beans = applicationContext.getBeanDefinitionNames();
    for (String o : beans) {
      logger.debug("________________________");
      logger.debug("BEAN id: '{}'", o);
      logger.debug("\tType: '{}'", applicationContext.getType(o));
      String[] aliases = applicationContext.getAliases(o);
      if (factory.isFactoryBean(o)) logger.debug("\tFACTORY");
      if (aliases != null && aliases.length > 0) {
        for (String a : aliases) {
          logger.debug("\tAliased as: '{}'", a);
        }
      }
      if (factory.getBeanDefinition(o).isAbstract()) {
        logger.debug("\tABSTRACT");
      } else {
        if (applicationContext.isPrototype(o)) logger.debug("\tScope: 'Prototype'");
        if (applicationContext.isSingleton(o)) logger.debug("\tScope: 'Singleton'");

        Annotation[] annotations = applicationContext.getBean(o).getClass().getAnnotations();
        if (annotations != null && annotations.length > 0) {
          logger.debug("\tAnnotations:");

          for (Annotation annotation : annotations) {
            logger.debug("\t\t'{}'", annotation.annotationType());
          }
        }
        if (!applicationContext
            .getBean(o)
            .toString()
            .startsWith(applicationContext.getType(o).toString() + "@")) {
          logger.debug("\tContents: {}", applicationContext.getBean(o).toString());
        }
      }
    }

    logger.debug("******************************************************************************");
    logger.debug("*** Number of Beans={} ***", applicationContext.getBeanDefinitionCount());
    logger.debug("*** Number of Bean Post Processors={} ***", factory.getBeanPostProcessorCount());
    logger.debug("******************************************************************************");
  }
Ejemplo n.º 2
0
  private void initApiInfo() throws Exception {
    int apiCounter = 0;
    String[] beanNames = applicationContext.getBeanNamesForAnnotation(Controller.class);

    if (beanNames == null) {
      logger.info("No controller bean found. stop server and fix it.");
      throw new Exception("No controller bean found. stop server and fix it.");
    }

    Map<String, Object> checkMap = new HashMap<String, Object>();
    for (String beanName : beanNames) {
      logger.info("Controller bean found: " + beanName);
      Class<?> beanType = applicationContext.getType(beanName);

      Method[] methods = beanType.getMethods();
      for (Method method : methods) {
        if (method.getAnnotation(Api.class) != null
            && method.getAnnotation(RequestMapping.class) != null) {
          logger.info("Controller Api Method found: " + method.getName());
          if (checkMap.get(method.getName()) != null) {
            logger.info("Controller method name is duplicated! stop server and fix it.");
            throw new Exception("Controller method name is duplicated! stop server and fix it.");
          }
          checkMap.put(method.getName(), new Object());
          apiCounter++;
        }
      }
    }
    logger.info("Total {} api listed.", apiCounter);
    this.apiInfoCache = new ConcurrentHashMap<String, ApiInfo>();
  }
  private static String getBeanName(
      ComponentContext cc, Class<?> c, ApplicationContext springContext) {
    boolean annotatedWithInject = false;
    if (cc != null) {
      final Inject inject = getAnnotation(cc.getAnnotations(), Inject.class);
      if (inject != null) {
        annotatedWithInject = true;
        if (inject.value() != null && !inject.value().equals("")) {
          return inject.value();
        }
      }
    }

    final String names[] = BeanFactoryUtils.beanNamesForTypeIncludingAncestors(springContext, c);

    if (names.length == 0) {
      return null;
    } else if (names.length == 1) {
      return names[0];
    } else {
      // Check if types of the beans names are assignable
      // Spring auto-registration for a type A will include the bean
      // names for classes that extend A
      boolean inheritedNames = false;
      String beanName = null;
      for (String name : names) {
        Class<?> beanType = ClassUtils.getUserClass(springContext.getType(name));

        inheritedNames = c.isAssignableFrom(beanType);

        if (c == beanType) beanName = name;
      }

      if (inheritedNames) {
        if (beanName != null) return beanName;
      }

      final StringBuilder sb = new StringBuilder();
      sb.append("There are multiple beans configured in spring for the type ")
          .append(c.getName())
          .append(".");

      if (annotatedWithInject) {
        sb.append(
            "\nYou should specify the name of the preferred bean at @Inject: Inject(\"yourBean\").");
      } else {
        sb.append(
            "\nAnnotation information was not available, the reason might be because you're not using "
                + "@Inject. You should use @Inject and specifiy the bean name via Inject(\"yourBean\").");
      }

      sb.append("\nAvailable bean names: ").append(toCSV(names));

      throw new RuntimeException(sb.toString());
    }
  }
Ejemplo n.º 4
0
 @SuppressWarnings("unchecked")
 @Override
 public Class<? extends UI> getUIClass(UIClassSelectionEvent event) {
   ApplicationContext context = SpringApplicationContext.getApplicationContext();
   if (context != null) {
     return (Class<? extends UI>) context.getType(getUIBeanName(event.getRequest()));
   } else {
     return null;
   }
 }
Ejemplo n.º 5
0
  public static void main(String[] args) {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] {"beans.xml"});
    //
    // Alternatively you can get the bean by name like this:
    //
    // Action action = (Action) context.getBean("printAction");
    //
    Action action = context.getBean(Action.class);
    action.execute("Hello, world!");

    System.out.println();

    // this is how you get the list of all beans in a context:
    String[] beans = context.getBeanDefinitionNames();
    for (String bean : beans) {
      System.out.println(String.format("%s: %s", bean, context.getType(bean)));
    }
  }
Ejemplo n.º 6
0
 /** 加载bean, */
 @SuppressWarnings("unchecked")
 private void initBeans() {
   String[] beanNames = applicationContext.getBeanDefinitionNames();
   for (String beanName : beanNames) {
     if (applicationContext.getBean(beanName)
         instanceof
         Interceptor /*||applicationContext.getType(beanName).isAnnotationPresent(org.majorxie.dreamvc.annotation.Interceptor.class)==true*/) {
       // applicationContext.getBean(beanName, Interceptor.class);
       interceptorBeans.add(applicationContext.getBean(beanName));
       log.info("init interceptor..");
     } else if (applicationContext.getBean(beanName) instanceof Controller
         || applicationContext
                 .getType(beanName)
                 .isAnnotationPresent(org.majorxie.dreamvc.annotation.Controller.class)
             == true) {
       controllerBeans.add(applicationContext.getBean(beanName));
       log.info("init controller....");
     } else {
       otherBeans.add(applicationContext.getBean(beanName));
       log.info("init others...");
     }
   }
 }
 @SuppressWarnings("unchecked")
 @Override
 public Class<? extends Actor> actorClass() {
   return (Class<? extends Actor>) applicationContext.getType(actorBeanName);
 }
Ejemplo n.º 8
0
  /**
   * 检查上下文中的BOP服务方法
   *
   * @throws org.springframework.beans.BeansException
   */
  private void registerFromContext(final ApplicationContext context) throws BeansException {
    if (logger.isDebugEnabled()) {
      logger.debug("对Spring上下文中的Bean进行扫描,查找ROP服务方法: " + context);
    }
    String[] beanNames = context.getBeanNamesForType(Object.class);
    for (final String beanName : beanNames) {
      Class<?> handlerType = context.getType(beanName);
      ReflectionUtils.doWithMethods(
          handlerType,
          new ReflectionUtils.MethodCallback() {
            public void doWith(Method method)
                throws IllegalArgumentException, IllegalAccessException {
              ReflectionUtils.makeAccessible(method);

              ServiceMethod serviceMethod = method.getAnnotation(ServiceMethod.class);
              ServiceMethodGroup serviceMethodGroup =
                  method.getDeclaringClass().getAnnotation(ServiceMethodGroup.class);

              ServiceMethodDefinition definition = null;
              if (serviceMethodGroup != null) {
                definition = buildServiceMethodDefinition(serviceMethodGroup, serviceMethod);
              } else {
                definition = buildServiceMethodDefinition(serviceMethod);
              }
              ServiceMethodHandler serviceMethodHandler = new ServiceMethodHandler();
              serviceMethodHandler.setServiceMethodDefinition(definition);

              // 1.set handler
              serviceMethodHandler.setHandler(context.getBean(beanName)); // handler
              serviceMethodHandler.setHandlerMethod(method); // handler'method
              if (method.getParameterTypes().length > 0) { // handler method's parameter
                Class<?> aClass = method.getParameterTypes()[0];
                Assert.isAssignable(RopRequest.class, aClass, "@ServiceMethod方法入参必须是RopRequest");
                serviceMethodHandler.setRequestType((Class<? extends RopRequest>) aClass);
              }

              // 2.set sign fieldNames
              serviceMethodHandler.setIgnoreSignFieldNames(
                  getIgnoreSignFieldNames(serviceMethodHandler.getRequestType()));

              addServiceMethod(
                  serviceMethod.value(), serviceMethod.version(), serviceMethodHandler);

              if (logger.isDebugEnabled()) {
                logger.debug(
                    "注册服务方法:"
                        + method.getDeclaringClass().getCanonicalName()
                        + "#"
                        + method.getName()
                        + "(..)");
              }
            }
          },
          new ReflectionUtils.MethodFilter() {
            public boolean matches(Method method) {
              return AnnotationUtils.findAnnotation(method, ServiceMethod.class) != null;
            }
          });
    }
    if (context.getParent() != null) {
      registerFromContext(context.getParent());
    }
    if (logger.isInfoEnabled()) {
      logger.info("共注册了" + serviceHandlerMap.size() + "个服务方法");
    }
  }
Ejemplo n.º 9
0
 /**
  * @param name
  * @return Class 注册对象的类型
  * @throws NoSuchBeanDefinitionException
  */
 public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
   return applicationContext.getType(name);
 }
Ejemplo n.º 10
0
 public Class<?> getType(String arg0) throws NoSuchBeanDefinitionException {
   return applicationContext.getType(arg0);
 }