private void testBeanDefinitions(BeanDefinitionRegistry registry) {
   assertEquals(24, registry.getBeanDefinitionCount());
   assertEquals(24, registry.getBeanDefinitionNames().length);
   assertTrue(Arrays.asList(registry.getBeanDefinitionNames()).contains("rod"));
   assertTrue(Arrays.asList(registry.getBeanDefinitionNames()).contains("aliased"));
   assertTrue(registry.containsBeanDefinition("rod"));
   assertTrue(registry.containsBeanDefinition("aliased"));
   assertEquals(TestBean.class.getName(), registry.getBeanDefinition("rod").getBeanClassName());
   assertEquals(
       TestBean.class.getName(), registry.getBeanDefinition("aliased").getBeanClassName());
   assertTrue(registry.isAlias("youralias"));
   assertEquals(2, registry.getAliases("aliased").length);
   assertEquals("myalias", registry.getAliases("aliased")[0]);
   assertEquals("youralias", registry.getAliases("aliased")[1]);
 }
 private String getResourceDescription(String beanName, ListableBeanFactory beanFactory) {
   if (beanFactory instanceof BeanDefinitionRegistry) {
     BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
     return registry.getBeanDefinition(beanName).getResourceDescription();
   }
   return "unknown";
 }
 @Override
 public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
     throws BeansException {
   Collection<Class<?>> remotingServices = new HashSet<Class<?>>();
   remotingServices.addAll(getIncludeClasses());
   String[] basePackages = getBasePackages();
   if (basePackages != null)
     remotingServices.addAll(ClassScanner.scanAnnotated(basePackages, Remoting.class));
   Collection<Class<?>> excludeRemotingServices = getExcludeClasses();
   for (Class<?> remotingService : remotingServices) {
     if (!remotingService.isInterface() || excludeRemotingServices.contains(remotingService))
       continue;
     String beanName = StringUtils.uncapitalize(remotingService.getSimpleName());
     if (registry.containsBeanDefinition(beanName)) {
       logger.info(
           "Skip bean {} which implemented by {}",
           beanName,
           registry.getBeanDefinition(beanName).getBeanClassName());
       continue;
     }
     RootBeanDefinition beanDefinition = new RootBeanDefinition(HttpInvokerClient.class);
     beanDefinition.setTargetType(remotingService);
     beanDefinition.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_BY_NAME);
     MutablePropertyValues propertyValues = new MutablePropertyValues();
     propertyValues.addPropertyValue("serviceInterface", remotingService.getName());
     beanDefinition.setPropertyValues(propertyValues);
     registry.registerBeanDefinition(beanName, beanDefinition);
     logger.info("Registered bean {} for remoting service", beanName);
   }
 }
예제 #4
0
 private void initWildcardDefinitionMap() {
   if (null != appContexts) {
     for (ApplicationContext appContext : appContexts) {
       for (String n : appContext.getBeanDefinitionNames()) {
         if (isWildcardBeanName(n)) {
           AutowireCapableBeanFactory bf = appContext.getAutowireCapableBeanFactory();
           BeanDefinitionRegistry bdr = (BeanDefinitionRegistry) bf;
           BeanDefinition bd = bdr.getBeanDefinition(n);
           String className = bd.getBeanClassName();
           if (null != className) {
             String orig = n;
             if (n.charAt(0) == '*') {
               // old wildcard
               n = "." + n.replaceAll("\\.", "\\.");
             }
             try {
               Matcher matcher = Pattern.compile(n).matcher("");
               List<MatcherHolder> m = wildCardBeanDefinitions.get(className);
               if (m == null) {
                 m = new ArrayList<MatcherHolder>();
                 wildCardBeanDefinitions.put(className, m);
               }
               MatcherHolder holder = new MatcherHolder(orig, matcher);
               m.add(holder);
             } catch (PatternSyntaxException npe) {
               // not a valid patter, we'll ignore
             }
           } else {
             LOG.warn("Wildcars with not class {}", n);
           }
         }
       }
     }
   }
 }
  @Override
  protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
    Assert.notEmpty(basePackages, "At least one base package must be specified");
    Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
    for (String basePackage : basePackages) {
      Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
      for (BeanDefinition candidate : candidates) {
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
        candidate.setScope(scopeMetadata.getScopeName());
        String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
        if (candidate instanceof AbstractBeanDefinition) {
          postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
        }
        if (candidate instanceof AnnotatedBeanDefinition) {
          processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
        }

        ScannedGenericBeanDefinition bd = (ScannedGenericBeanDefinition) candidate; // 通用bean扫描
        bd.setBeanClassName(HessianServiceExporter.class.getName()); // 设置bean名称
        bd.setBeanClass(HessianServiceExporter.class); // 设置bean类
        bd.getPropertyValues().add("service", registry.getBeanDefinition(beanName)); // 设置属性 service
        String[] interfaces = bd.getMetadata().getInterfaceNames(); // 获得元数据、接口名称

        if (interfaces == null || interfaces.length == 0) continue;
        Class interf = null;
        try {
          interf = Class.forName(interfaces[0]); // 获得接口
        } catch (ClassNotFoundException e) {
          continue;
        }
        bd.getPropertyValues().add("serviceInterface", interf); // 设置属性 serviceInterface
        candidate = bd;
        BeanDefinitionHolder definitionHolder =
            new BeanDefinitionHolder(candidate, "/" + beanName); // 新bean定义持有
        definitionHolder =
            applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry); // 应用范围代理模式
        beanDefinitions.add(definitionHolder); // 将bean定义持有放入bean定义持有set中
        registerBeanDefinition(definitionHolder, this.registry); // 注册bean定义
      }
    }

    if (beanDefinitions.isEmpty()) {
      System.out.println("not service be scaned");
    } else {
      for (BeanDefinitionHolder holder : beanDefinitions) {
        AnnotatedBeanDefinition definition =
            (AnnotatedBeanDefinition) holder.getBeanDefinition(); // 注释的bean定义
        System.out.println("service:" + holder.getBeanName()); // 注释的bean定义名称
        System.out.println(
            "service:" + definition.getMetadata().getAnnotationTypes()); // 注释的bean定义类型
      }
    }

    return beanDefinitions;
  }
  /**
   * Returns the bean name of a {@link MappingContext} to be wired. Will inspect the namespace
   * attribute first and if no config is found in that place it will try to lookup the default one.
   * Will return {@literal null} if neither one is available.
   *
   * @param config
   * @param registry
   * @return
   */
  private String getMappingContextReference(
      MongoRepositoryConfiguration config, BeanDefinitionRegistry registry) {

    String contextRef = config.getMappingContextRef();

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

    try {
      registry.getBeanDefinition(MAPPING_CONTEXT_DEFAULT);
      return MAPPING_CONTEXT_DEFAULT;
    } catch (NoSuchBeanDefinitionException e) {
      return null;
    }
  }
 /**
  * Register the specified entity scan packages with the system.
  *
  * @param registry the source registry
  * @param packageNames the package names to register
  */
 public static void register(BeanDefinitionRegistry registry, Collection<String> packageNames) {
   Assert.notNull(registry, "Registry must not be null");
   Assert.notNull(packageNames, "PackageNames must not be null");
   if (registry.containsBeanDefinition(BEAN)) {
     BeanDefinition beanDefinition = registry.getBeanDefinition(BEAN);
     ConstructorArgumentValues constructorArguments =
         beanDefinition.getConstructorArgumentValues();
     constructorArguments.addIndexedArgumentValue(
         0, addPackageNames(constructorArguments, packageNames));
   } else {
     GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
     beanDefinition.setBeanClass(EntityScanPackages.class);
     beanDefinition
         .getConstructorArgumentValues()
         .addIndexedArgumentValue(0, packageNames.toArray(new String[packageNames.size()]));
     beanDefinition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
     registry.registerBeanDefinition(BEAN, beanDefinition);
   }
 }
  private void parseGrailsApplication(
      Element element,
      ParserContext parserContext,
      XmlReaderContext readerContext,
      ClassLoader beanClassLoader,
      String[] basePackages) {

    BeanDefinitionRegistry simpleRegistry = new SimpleBeanDefinitionRegistry();
    ClassPathBeanDefinitionScanner scanner = configureScanner(parserContext, simpleRegistry);

    scanner.scan(basePackages);

    BeanDefinitionRegistry targetRegistry = parserContext.getRegistry();
    AbstractBeanDefinition grailsApplicationBean = new GenericBeanDefinition();
    grailsApplicationBean.setBeanClass(DefaultGrailsApplication.class);
    grailsApplicationBean.setInitMethodName("initialise");
    ConstructorArgumentValues constructorArgs =
        grailsApplicationBean.getConstructorArgumentValues();

    Set<Class<?>> classes = new HashSet<Class<?>>();
    for (String beanName : simpleRegistry.getBeanDefinitionNames()) {
      BeanDefinition beanDef = simpleRegistry.getBeanDefinition(beanName);
      try {
        Class<?> entityClass = Class.forName(beanDef.getBeanClassName(), true, beanClassLoader);
        classes.add(entityClass);
        registerDomainBean(
            entityClass, targetRegistry, element.getAttribute(MESSAGE_SOURCE_ATTRIBUTE));
      } catch (ClassNotFoundException e) {
        throw new BeanDefinitionParsingException(
            new Problem(
                "Unable to load class whilst configuring GORM: " + e.getMessage(),
                new Location(readerContext.getResource()),
                null,
                e));
      }
    }

    constructorArgs.addGenericArgumentValue(classes.toArray(new Class[classes.size()]));
    constructorArgs.addGenericArgumentValue(beanClassLoader);
    targetRegistry.registerBeanDefinition(GrailsApplication.APPLICATION_ID, grailsApplicationBean);
  }
  /**
   * Read a particular {@link ConfigurationClassMethod}, registering bean definitions with the
   * BeanDefinitionRegistry based on its contents.
   */
  private void loadBeanDefinitionsForBeanMethod(ConfigurationClassMethod beanMethod) {
    ConfigurationClass configClass = beanMethod.getConfigurationClass();
    MethodMetadata metadata = beanMethod.getMetadata();

    RootBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass);
    beanDef.setResource(configClass.getResource());
    beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
    beanDef.setFactoryBeanName(configClass.getBeanName());
    beanDef.setUniqueFactoryMethodName(metadata.getMethodName());
    beanDef.setAutowireMode(RootBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    beanDef.setAttribute(
        RequiredAnnotationBeanPostProcessor.SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);

    // consider name and any aliases
    Map<String, Object> beanAttributes = metadata.getAnnotationAttributes(Bean.class.getName());
    List<String> names =
        new ArrayList<String>(Arrays.asList((String[]) beanAttributes.get("name")));
    String beanName =
        (names.size() > 0 ? names.remove(0) : beanMethod.getMetadata().getMethodName());
    for (String alias : names) {
      this.registry.registerAlias(beanName, alias);
    }

    // has this already been overridden (e.g. via XML)?
    if (this.registry.containsBeanDefinition(beanName)) {
      BeanDefinition existingBeanDef = registry.getBeanDefinition(beanName);
      // is the existing bean definition one that was created from a configuration class?
      if (!(existingBeanDef instanceof ConfigurationClassBeanDefinition)) {
        // no -> then it's an external override, probably XML
        // overriding is legal, return immediately
        if (logger.isDebugEnabled()) {
          logger.debug(
              String.format(
                  "Skipping loading bean definition for %s: a definition for bean "
                      + "'%s' already exists. This is likely due to an override in XML.",
                  beanMethod, beanName));
        }
        return;
      }
    }

    if (metadata.isAnnotated(Primary.class.getName())) {
      beanDef.setPrimary(true);
    }

    // is this bean to be instantiated lazily?
    if (metadata.isAnnotated(Lazy.class.getName())) {
      beanDef.setLazyInit(
          (Boolean) metadata.getAnnotationAttributes(Lazy.class.getName()).get("value"));
    } else if (configClass.getMetadata().isAnnotated(Lazy.class.getName())) {
      beanDef.setLazyInit(
          (Boolean)
              configClass.getMetadata().getAnnotationAttributes(Lazy.class.getName()).get("value"));
    }

    if (metadata.isAnnotated(DependsOn.class.getName())) {
      String[] dependsOn =
          (String[]) metadata.getAnnotationAttributes(DependsOn.class.getName()).get("value");
      if (dependsOn.length > 0) {
        beanDef.setDependsOn(dependsOn);
      }
    }

    Autowire autowire = (Autowire) beanAttributes.get("autowire");
    if (autowire.isAutowire()) {
      beanDef.setAutowireMode(autowire.value());
    }

    String initMethodName = (String) beanAttributes.get("initMethod");
    if (StringUtils.hasText(initMethodName)) {
      beanDef.setInitMethodName(initMethodName);
    }

    String destroyMethodName = (String) beanAttributes.get("destroyMethod");
    if (StringUtils.hasText(destroyMethodName)) {
      beanDef.setDestroyMethodName(destroyMethodName);
    }

    // consider scoping
    ScopedProxyMode proxyMode = ScopedProxyMode.NO;
    Map<String, Object> scopeAttributes = metadata.getAnnotationAttributes(Scope.class.getName());
    if (scopeAttributes != null) {
      beanDef.setScope((String) scopeAttributes.get("value"));
      proxyMode = (ScopedProxyMode) scopeAttributes.get("proxyMode");
      if (proxyMode == ScopedProxyMode.DEFAULT) {
        proxyMode = ScopedProxyMode.NO;
      }
    }

    // replace the original bean definition with the target one, if necessary
    BeanDefinition beanDefToRegister = beanDef;
    if (proxyMode != ScopedProxyMode.NO) {
      BeanDefinitionHolder proxyDef =
          ScopedProxyCreator.createScopedProxy(
              new BeanDefinitionHolder(beanDef, beanName),
              this.registry,
              proxyMode == ScopedProxyMode.TARGET_CLASS);
      beanDefToRegister = proxyDef.getBeanDefinition();
    }

    if (logger.isDebugEnabled()) {
      logger.debug(
          String.format(
              "Registering bean definition for @Bean method %s.%s()",
              configClass.getMetadata().getClassName(), beanName));
    }

    registry.registerBeanDefinition(beanName, beanDefToRegister);
  }