private Object findAutowireCandidateOfType(Class<?> beanType) {
   String[] candidates = applicationContext.getBeanNamesForType(beanType);
   String primary = null;
   AutowireCapableBeanFactory beanFactory = applicationContext.getAutowireCapableBeanFactory();
   if (beanFactory instanceof ConfigurableListableBeanFactory) {
     for (String bean : candidates) {
       final ConfigurableListableBeanFactory clBeanFactory =
           (ConfigurableListableBeanFactory) beanFactory;
       if (clBeanFactory.containsBeanDefinition(bean)
           && clBeanFactory.getBeanDefinition(bean).isPrimary()) {
         if (primary != null) {
           throw new IllegalStateException(
               format(
                   "More than one bean of type [%s] marked as primary. " + "Found '%s' and '%s'.",
                   beanType.getName(), primary, bean));
         }
         primary = bean;
       }
     }
   }
   if (primary == null && candidates.length == 1) {
     primary = candidates[0];
   } else if (primary == null && candidates.length > 1) {
     throw new IllegalStateException(
         "More than one bean of type ["
             + beanType.getName()
             + "] is eligible for autowiring, "
             + "and none of them is marked as primary.");
   }
   return primary == null ? null : applicationContext.getBean(primary);
 }
  @Override
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = applicationContext;

    // Gets all of the Validator beans from the application Context.
    Map<String, Validator> beanValidators = applicationContext.getBeansOfType(Validator.class);
    String[] mnbDaoBeans = applicationContext.getBeanNamesForType(BaseDao.class);

    for (int i = 0; i < mnbDaoBeans.length; i++) {

      // Gets the Class type that the Dao handles
      BaseDao type = (BaseDao) applicationContext.getBean(mnbDaoBeans[i]);

      Iterator<String> itr = beanValidators.keySet().iterator();
      List<Validator> validators = new ArrayList<Validator>();
      while (itr.hasNext()) {
        String key = itr.next();
        Validator validator = beanValidators.get(key);

        if (validator.supports(type.getEntityClass())) {
          validators.add(validator);
        }
      }

      if (validators.size() > 0) {
        this.cachedValidatorsMap.put(type.getEntityClass(), validators);
      }
    }

    logger.info("Validation Framework is bootstrapped and ready to roll");
  }
 /**
  * Creates list of instances of DAO
  *
  * @throws Exception
  */
 public void afterPropertiesSet() throws Exception {
   String[] beanNamesForType = context.getBeanNamesForType(ExperimentDao.class);
   for (String name : beanNamesForType) {
     gDaoList.add((GenericDao) context.getBean(name));
     //  break; // ???
   }
 }
  /**
   * Reads the new error handler from the newly created application context and loads it into this
   * manager.
   *
   * @param newServiceContext newly created application context
   */
  protected void loadNewErrorHandler(ApplicationContext newServiceContext) {
    String[] errorBeanNames = newServiceContext.getBeanNamesForType(AbstractErrorHandler.class);
    log.debug("{}: Loading {} new error handler.", getId(), errorBeanNames.length);

    errorHandler = (AbstractErrorHandler) newServiceContext.getBean(errorBeanNames[0]);
    log.debug(
        "{}: Loaded new error handler of type: {}", getId(), errorHandler.getClass().getName());
  }
 private EndpointHandlerMapping getRequiredEndpointHandlerMapping() {
   EndpointHandlerMapping endpointHandlerMapping = null;
   ApplicationContext context = this.contextResolver.getApplicationContext();
   if (context.getBeanNamesForType(EndpointHandlerMapping.class).length > 0) {
     endpointHandlerMapping = context.getBean(EndpointHandlerMapping.class);
   }
   if (endpointHandlerMapping == null) {
     // Maybe there are actually no endpoints (e.g. management.port=-1)
     endpointHandlerMapping = new EndpointHandlerMapping(Collections.<MvcEndpoint>emptySet());
   }
   return endpointHandlerMapping;
 }
Example #6
0
 public <T> T getBean(Class<T> requiredType) {
   String[] beanNames = applicationContext.getBeanNamesForType(requiredType);
   if (beanNames == null || beanNames.length == 0) {
     throw new NoSuchBeanDefinitionException(
         requiredType, "No bean of the required type was found.");
   }
   if (beanNames.length > 1) {
     throw new BeanDefinitionValidationException(
         "There are more than "
             + beanNames.length
             + "beans implementing the required type. "
             + "Use 'getBeanByName(String)' or getBean(String, Class) instead.");
   }
   return (T) getBean(beanNames[0], requiredType);
 }
Example #7
0
  public void init() throws TddlException {
    if (virtualTableMap == null || virtualTableMap.isEmpty()) {
      // 如果为空,采用自动查找的方式,将bean name做为逻辑表名
      Map<String, TableRule> vts = new HashMap<String, TableRule>();
      String[] tbeanNames = context.getBeanNamesForType(TableRule.class);
      for (String name : tbeanNames) {
        Object obj = context.getBean(name);
        vts.put(name, (TableRule) obj);
      }
      setTableRules(vts);
    }

    for (Map.Entry<String, TableRule> entry : virtualTableMap.entrySet()) {
      if (!lazyInit) {
        initTableRule(entry.getKey(), entry.getValue());
      }
    }
  }
  /**
   * Reads the new authentication handlers from the newly created application context and loads it
   * into this manager.
   *
   * @param newServiceContext newly created application context
   */
  protected void loadNewLoginHandlers(ApplicationContext newServiceContext) {
    String[] authnBeanNames = newServiceContext.getBeanNamesForType(LoginHandler.class);
    log.debug("{}: Loading {} new authentication handlers.", getId(), authnBeanNames.length);

    Map<String, LoginHandler> newLoginHandlers = new HashMap<String, LoginHandler>();
    LoginHandler authnHandler;
    for (String authnBeanName : authnBeanNames) {
      authnHandler = (LoginHandler) newServiceContext.getBean(authnBeanName);
      log.debug(
          "{}: Loading authentication handler of type supporting authentication methods: {}",
          getId(),
          authnHandler.getSupportedAuthenticationMethods());

      for (String authnMethod : authnHandler.getSupportedAuthenticationMethods()) {
        newLoginHandlers.put(authnMethod, authnHandler);
      }
    }
    loginHandlers = newLoginHandlers;
  }
Example #9
0
  @SuppressWarnings("unchecked")
  @Override
  public <T> T get(final Class<T> type) {
    final T candidateComponent = super.get(type);

    if (candidateComponent != null) {
      return candidateComponent;
    }

    final String[] names = applicationContext.getBeanNamesForType(type);

    if (names.length >= 1) {
      if ((names.length > 1) && LOGGER.isWarnEnabled()) {
        LOGGER.warn("Multiple beans for type {} found. Returning the first result.", type);
      }

      return (T) applicationContext.getBean(names[0]);
    }
    return null;
  }
  /**
   * Reads the new profile handlers from the newly created application context and loads it into
   * this manager.
   *
   * @param newServiceContext newly created application context
   */
  protected void loadNewProfileHandlers(ApplicationContext newServiceContext) {
    String[] profileBeanNames =
        newServiceContext.getBeanNamesForType(AbstractRequestURIMappedProfileHandler.class);
    log.debug("{}: Loading {} new profile handlers.", getId(), profileBeanNames.length);

    Map<String, AbstractRequestURIMappedProfileHandler> newProfileHandlers =
        new HashMap<String, AbstractRequestURIMappedProfileHandler>();
    AbstractRequestURIMappedProfileHandler<?, ?> profileHandler;
    for (String profileBeanName : profileBeanNames) {
      profileHandler =
          (AbstractRequestURIMappedProfileHandler) newServiceContext.getBean(profileBeanName);
      for (String requestPath : profileHandler.getRequestPaths()) {
        newProfileHandlers.put(requestPath, profileHandler);
        log.debug(
            "{}: Loaded profile handler for handling requests to request path {}",
            getId(),
            requestPath);
      }
    }
    profileHandlers = newProfileHandlers;
  }
Example #11
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() + "个服务方法");
    }
  }
 @Test
 public void getBeanNamesForType() {
   String[] res = context.getBeanNamesForType(Person.class);
   logger.debug("res={}", res.toString());
 }
    /** {@inheritDoc} */
    @Override
    protected Map<String, Object> getDataMap(Context context) {

      final ApplicationContext factory = getApplicationContext(targetResource);

      Map<String, Object> map = new HashMap<String, Object>();

      Object value = context.getDefaultParameter();
      Map<String, String> idMap = new HashMap<String, String>();

      if (value instanceof Map) {
        for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) {
          Object k = entry.getKey();
          Object v = entry.getValue();
          if (v == null) {
            v = k;
          }
          idMap.put(k.toString(), v.toString());
        }
      } else {
        for (String part : parseDelimitedString(value, null)) {
          final int pos = part.indexOf('=');
          if (pos < 0) {
            throw new PaxmlRuntimeException("No '=' sign found for id mapping from line: " + part);
          }
          idMap.put(part.substring(0, pos), part.substring(pos + 1));
        }
      }
      Set<String> exclude =
          new HashSet<String>(parseDelimitedString(context.getConst(EXCLUDE, false), DELEMITER));
      Set<String> include =
          new HashSet<String>(parseDelimitedString(context.getConst(INCLUDE, false), DELEMITER));

      Set<String> excludeType =
          new HashSet<String>(
              parseDelimitedString(context.getConst(EXCLUDE_TYPE, false), DELEMITER));
      Set<String> includeType =
          new HashSet<String>(
              parseDelimitedString(context.getConst(INCLUDE_TYPE, false), DELEMITER));

      if (include.size() <= 0 && includeType.size() <= 0) {
        include.addAll(Arrays.asList(factory.getBeanDefinitionNames()));
      }

      for (String className : includeType) {
        for (String id :
            factory.getBeanNamesForType(ReflectUtils.loadClassStrict(className, null))) {
          include.add(id);
        }
      }
      for (String className : excludeType) {
        for (String id :
            factory.getBeanNamesForType(ReflectUtils.loadClassStrict(className, null))) {
          exclude.add(id);
        }
      }

      include.removeAll(exclude);

      for (String name : include) {

        Object bean = factory.getBean(name);
        if (bean != null) {
          String id = idMap.get(name);
          if (id == null) {
            id = name;
          }
          map.put(id, bean);
        }
      }

      return map;
    }
 public String[] getScheduleTaskDealList() {
   return applicationcontext.getBeanNamesForType(IScheduleTaskDeal.class);
 }
Example #15
0
 public String[] getBeanNamesForType(Class<?> arg0) {
   return applicationContext.getBeanNamesForType(arg0);
 }
Example #16
0
 public String[] getBeanNamesForType(Class<?> arg0, boolean arg1, boolean arg2) {
   return applicationContext.getBeanNamesForType(arg0, arg1, arg2);
 }