/**
  * Perform a scan within the specified base packages, returning the registered bean definitions.
  *
  * <p>This method does <i>not</i> register an annotation config processor but rather leaves this
  * up to the caller.
  *
  * @param basePackages the packages to check for annotated classes
  * @return set of beans registered if any for tooling registration purposes (never {@code null})
  */
 protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
   Assert.notEmpty(basePackages, "At least one base package must be specified");
   Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>();
   mylog.debug("遍历basePackages,获取包路径下面的.class所有类");
   for (String basePackage : basePackages) {
     Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
     mylog.debug("获取到有注解的bean集合并遍历,每个bean设置scope");
     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) {
         AnnotationConfigUtils.processCommonDefinitionAnnotations(
             (AnnotatedBeanDefinition) candidate);
       }
       if (checkCandidate(beanName, candidate)) {
         BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
         definitionHolder =
             AnnotationConfigUtils.applyScopedProxyMode(
                 scopeMetadata, definitionHolder, this.registry);
         beanDefinitions.add(definitionHolder);
         mylog.debug("登记AnnotatedBeanDefinition类型的bean");
         registerBeanDefinition(definitionHolder, this.registry);
       }
     }
   }
   return beanDefinitions;
 }
 /**
  * Determine whether the given new bean definition is compatible with the given existing bean
  * definition.
  *
  * <p>The default implementation considers them as compatible when the existing bean definition
  * comes from the same source or from a non-scanning source.
  *
  * @param newDefinition the new bean definition, originated from scanning
  * @param existingDefinition the existing bean definition, potentially an explicitly defined one
  *     or a previously generated one from scanning
  * @return whether the definitions are considered as compatible, with the new definition to be
  *     skipped in favor of the existing definition
  */
 protected boolean isCompatible(BeanDefinition newDefinition, BeanDefinition existingDefinition) {
   return (!(existingDefinition instanceof ScannedGenericBeanDefinition)
       || // explicitly registered overriding bean
       newDefinition.getSource().equals(existingDefinition.getSource())
       || // scanned same file twice
       newDefinition.equals(existingDefinition)); // scanned equivalent class twice
 }
  private void registerBeanDefinitionsWithRegistry(BeanDefinitionRegistry registry) {
    for (Object key : beanDefinitions.keySet()) {
      BeanDefinition bd = beanDefinitions.get(key);
      if (LOG.isDebugEnabled()) {
        LOG.debug("[RuntimeConfiguration] Registering bean [" + key + "]");
        if (LOG.isTraceEnabled()) {
          PropertyValue[] pvs = bd.getPropertyValues().getPropertyValues();
          for (PropertyValue pv : pvs) {
            LOG.trace(
                "[RuntimeConfiguration] With property ["
                    + pv.getName()
                    + "] set to ["
                    + pv.getValue()
                    + "]");
          }
        }
      }
      final String beanName = key.toString();
      if (registry.containsBeanDefinition(beanName)) {
        removeBeanDefinition(registry, beanName);
      }

      registry.registerBeanDefinition(beanName, bd);
      registerBeanAliases(registry, beanName);
    }
  }
예제 #4
0
  private void autoRegisterBeanDefinition(
      String id, BeanDefinition definition, ParserContext parserContext, String contextId) {
    // it is a bit cumbersome to work with the spring bean definition parser
    // as we kinda need to eagerly register the bean definition on the parser context
    // and then later we might find out that we should not have done that in case we have multiple
    // camel contexts
    // that would have a id clash by auto registering the same bean definition with the same id such
    // as a producer template

    // see if we have already auto registered this id
    BeanDefinition existing = autoRegisterMap.get(id);
    if (existing == null) {
      // no then add it to the map and register it
      autoRegisterMap.put(id, definition);
      parserContext.registerComponent(new BeanComponentDefinition(definition, id));
      if (LOG.isDebugEnabled()) {
        LOG.debug(
            "Registered default: {} with id: {} on camel context: {}",
            new Object[] {definition.getBeanClassName(), id, contextId});
      }
    } else {
      // ups we have already registered it before with same id, but on another camel context
      // this is not good so we need to remove all traces of this auto registering.
      // end user must manually add the needed XML elements and provide unique ids access all camel
      // context himself.
      LOG.debug(
          "Unregistered default: {} with id: {} as we have multiple camel contexts and they must use unique ids."
              + " You must define the definition in the XML file manually to avoid id clashes when using multiple camel contexts",
          definition.getBeanClassName(),
          id);

      parserContext.getRegistry().removeBeanDefinition(id);
    }
  }
  @SuppressWarnings({"unchecked"})
  private void parseProcessors(
      Element element, ParserContext parserContext, GenericBeanDefinition beanDefinition) {
    Element processorsElement =
        DomUtils.getChildElementByTagName(element, EVENT_PROCESSORS_ELEMENT);

    Element snapshotTriggerElement =
        DomUtils.getChildElementByTagName(element, SNAPSHOT_TRIGGER_ELEMENT);
    if (snapshotTriggerElement != null) {
      BeanDefinition triggerDefinition =
          snapshotterTriggerParser.parse(snapshotTriggerElement, parserContext);
      PropertyValue aggregateCache = beanDefinition.getPropertyValues().getPropertyValue("cache");
      if (aggregateCache != null) {
        triggerDefinition.getPropertyValues().add("aggregateCache", aggregateCache.getValue());
      }
      beanDefinition.getPropertyValues().add(SNAPSHOTTER_TRIGGER_PROPERTY, triggerDefinition);
    }

    if (processorsElement != null) {
      List<Object> processorsList =
          parserContext.getDelegate().parseListElement(processorsElement, beanDefinition);
      if (!processorsList.isEmpty()) {
        beanDefinition.getPropertyValues().add(EVENT_STREAM_DECORATORS_PROPERTY, processorsList);
      }
    }
  }
  @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);
    }
  }
예제 #7
0
 private void addDependsOnToRouteBuilder(
     Element childElement, ParserContext parserContext, String contextId) {
   // setting the depends-on explicitly is required since Spring 3.0
   String routeBuilderName = childElement.getAttribute("ref");
   if (ObjectHelper.isNotEmpty(routeBuilderName)) {
     // set depends-on to the context for a routeBuilder bean
     try {
       BeanDefinition definition = parserContext.getRegistry().getBeanDefinition(routeBuilderName);
       Method getDependsOn = definition.getClass().getMethod("getDependsOn", new Class[] {});
       String[] dependsOn = (String[]) getDependsOn.invoke(definition);
       if (dependsOn == null || dependsOn.length == 0) {
         dependsOn = new String[] {contextId};
       } else {
         String[] temp = new String[dependsOn.length + 1];
         System.arraycopy(dependsOn, 0, temp, 0, dependsOn.length);
         temp[dependsOn.length] = contextId;
         dependsOn = temp;
       }
       Method method = definition.getClass().getMethod("setDependsOn", String[].class);
       method.invoke(definition, (Object) dependsOn);
     } catch (Exception e) {
       // Do nothing here
     }
   }
 }
예제 #8
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);
           }
         }
       }
     }
   }
 }
  /** Register the {@link Configuration} class itself as a bean definition. */
  private void doLoadBeanDefinitionForConfigurationClassIfNecessary(
      ConfigurationClass configClass) {
    if (configClass.getBeanName() != null) {
      // a bean definition already exists for this configuration class -> nothing to do
      return;
    }

    // no bean definition exists yet -> this must be an imported configuration class (@Import).
    BeanDefinition configBeanDef = new GenericBeanDefinition();
    String className = configClass.getMetadata().getClassName();
    configBeanDef.setBeanClassName(className);
    if (checkConfigurationClassCandidate(configBeanDef, this.metadataReaderFactory)) {
      String configBeanName =
          BeanDefinitionReaderUtils.registerWithGeneratedName(configBeanDef, this.registry);
      configClass.setBeanName(configBeanName);
      if (logger.isDebugEnabled()) {
        logger.debug(
            String.format(
                "Registered bean definition for imported @Configuration class %s", configBeanName));
      }
    } else {
      try {
        MetadataReader reader = this.metadataReaderFactory.getMetadataReader(className);
        AnnotationMetadata metadata = reader.getAnnotationMetadata();
        this.problemReporter.error(
            new InvalidConfigurationImportProblem(className, reader.getResource(), metadata));
      } catch (IOException ex) {
        throw new IllegalStateException("Could not create MetadataReader for class " + className);
      }
    }
  }
예제 #10
0
  @Override
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
      throws BeansException {

    if (!(beanFactory instanceof DefaultListableBeanFactory)) {
      log.error("if speed up spring, bean factory must be type of DefaultListableBeanFactory");
      return;
    }

    DefaultListableBeanFactory listableBeanFactory = (DefaultListableBeanFactory) beanFactory;

    for (String beanName : listableBeanFactory.getBeanDefinitionNames()) {
      BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanName);

      // 如果匹配模式 就移除掉
      if (needRemove(beanName, beanDefinition)) {
        listableBeanFactory.removeBeanDefinition(beanName);
        continue;
      }

      // 否则设置为lazy
      if (needLazyInit(beanName)) {
        beanDefinition.setLazyInit(true);
      }
    }
  }
예제 #11
0
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactoryToProcess)
      throws BeansException {

    StringValueResolver valueResolver = new BeanDirectoryResolver();

    BeanDefinitionVisitor visitor = new BeanDefinitionVisitor(valueResolver);

    String[] beanNames = beanFactoryToProcess.getBeanDefinitionNames();
    for (int i = 0; i < beanNames.length; i++) {

      BeanDefinition bd = beanFactoryToProcess.getBeanDefinition(beanNames[i]);
      try {
        visitor.visitBeanDefinition(bd);
      } catch (BeanDefinitionStoreException ex) {
        throw new BeanDefinitionStoreException(
            bd.getResourceDescription(), beanNames[i], ex.getMessage());
      }
    }

    // New in Spring 2.5: resolve placeholders in alias target names and aliases as well.
    beanFactoryToProcess.resolveAliases(valueResolver);

    // New in Spring 3.0: resolve placeholders in embedded values such as annotation attributes.
    beanFactoryToProcess.addEmbeddedValueResolver(valueResolver);
  }
예제 #12
0
  public BeanDefinitionHolder decorate(
      Node node, BeanDefinitionHolder definition, ParserContext parserContext) {

    BeanDefinition bd = definition.getBeanDefinition();
    List<?> list = parserContext.getDelegate().parseListElement((Element) node, bd);
    bd.getPropertyValues().addPropertyValue(getPropertyName(node), list);
    return definition;
  }
예제 #13
0
 /** @param args */
 public static void main(String[] args) {
   ClassPathScanningCandidateComponentProvider provider =
       new ClassPathScanningCandidateComponentProvider(true);
   String basePackage = "com/doctor";
   Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
   for (BeanDefinition component : components) {
     System.out.printf("Component: %s\n", component.getBeanClassName());
   }
 }
예제 #14
0
  @SuppressWarnings("rawtypes")
  @Test
  public void metodo1() throws IllegalArgumentException, Exception {
    this.scanningProvider = new ClassPathScanningCandidateComponentProvider(false);
    this.scanningProvider.addIncludeFilter(
        new AnnotationTypeFilter(javax.persistence.Entity.class));

    List<Class<? extends Object>> classes = new ArrayList<Class<? extends Object>>();
    for (BeanDefinition beanDef : this.scanningProvider.findCandidateComponents("br.com")) {
      classes.add(Class.forName(beanDef.getBeanClassName()));
    }

    CLAZZ:
    for (Class clazz : classes) {

      Field listaCampo[] = clazz.getDeclaredFields();
      for (Field campo : listaCampo) {
        if (campo.getName().trim().equalsIgnoreCase("id")) {

          for (Annotation anotacao : campo.getAnnotations()) {
            if (anotacao.toString().contains("sequenceName")) {
              String array[] = anotacao.toString().split(",");
              String sequence = "";
              for (String item : array) {
                if (item.contains("sequenceName")) {
                  sequence = item.replace("sequenceName=", "");
                  break;
                }
              }
              if (sequence != null && !sequence.equals("")) {
                // Descobre o maior id do banco
                Integer ultimoId = dao.max(clazz);
                if (ultimoId == null) {
                  ultimoId = 1;
                }
                Session session = dao.getCurrentSession();

                String sql = "SELECT setval('SISFIE." + sequence.trim() + "', " + ultimoId + ");";

                if (duplicadas.contains(sequence.trim())) {
                  throw new IllegalArgumentException();
                }
                duplicadas.add(sequence.trim());
                session.createSQLQuery(sql).uniqueResult();
                sequences.add(new SelectItem(ultimoId, sequence.trim()));
                continue CLAZZ;
              }
            }
          }
        }
      }
    }
    System.out.println("Total :" + sequences.size());
    for (SelectItem item : sequences) {
      System.out.println(item.getLabel() + ": " + item.getValue());
    }
  }
 /**
  * Convenience method to update a template bean definition from overriding XML data. If <code>
  * overrides</code> contains attribute <code>attribute</code>, transfer that attribute onto <code>
  * template</code>, overwriting the default value.
  */
 public static String overrideAttribute(
     String attribute, BeanDefinition template, Element overrides) {
   String value = (String) template.getAttribute(attribute);
   if (overrides.hasAttribute(attribute)) {
     value = overrides.getAttribute(attribute);
     template.setAttribute(attribute, value);
   }
   return value;
 }
 @SuppressWarnings("unchecked")
 @Test
 public void initParameters() throws IOException {
   BeanDefinition servletRegistrationBean = getBeanDefinition(InitParametersServlet.class);
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat((Map<String, String>) propertyValues.get("initParameters"))
       .containsEntry("a", "alpha")
       .containsEntry("b", "bravo");
 }
  /*
   * JD: Overriding manually and playing with bean definitions. We do this
   * because we have not ported all the mock test data to a 2.x style configuration
   * directory, so we need to force the legacy data directory loader to engage.
   */
  protected void loadBeanDefinitions(XmlBeanDefinitionReader reader)
      throws BeansException, IOException {
    super.loadBeanDefinitions(reader);

    if (useLegacyGeoServerLoader) {
      BeanDefinition def = reader.getBeanFactory().getBeanDefinition("geoServerLoader");
      def.setBeanClassName("org.geoserver.test.TestGeoServerLoaderProxy");
    }
  }
  /**
   * Returns the name of the Bean as registered to Spring. Throws IllegalState exception if none or
   * more than one beans are found.
   *
   * @param ctx spring application context
   * @param clazz bean class
   * @param required true if the value is required
   * @throws IllegalStateException
   * @return spring name of the bean
   */
  private String getBeanNameOfClass(
      final ApplicationContext ctx, final Class<?> clazz, final boolean required) {
    // get the list of all possible matching beans
    List<String> names =
        new ArrayList<String>(
            Arrays.asList(BeanFactoryUtils.beanNamesForTypeIncludingAncestors(ctx, clazz)));

    // filter out beans that are not candidates for autowiring
    if (ctx instanceof AbstractApplicationContext) {
      Iterator<String> it = names.iterator();
      while (it.hasNext()) {
        final String possibility = it.next();
        BeanDefinition beanDef =
            getBeanDefinition(((AbstractApplicationContext) ctx).getBeanFactory(), possibility);
        if (BeanFactoryUtils.isFactoryDereference(possibility)
            || possibility.startsWith("scopedTarget.")
            || (beanDef != null && !beanDef.isAutowireCandidate())) {
          it.remove();
        }
      }
    }

    if (names.isEmpty()) {
      if (required) {
        throw new IllegalStateException("bean of type [" + clazz.getName() + "] not found");
      }
      return null;
    } else if (names.size() > 1) {
      if (ctx instanceof AbstractApplicationContext) {
        List<String> primaries = new ArrayList<String>();
        for (String name : names) {
          BeanDefinition beanDef =
              getBeanDefinition(((AbstractApplicationContext) ctx).getBeanFactory(), name);
          if (beanDef instanceof AbstractBeanDefinition) {
            if (beanDef.isPrimary()) {
              primaries.add(name);
            }
          }
        }
        if (primaries.size() == 1) {
          return primaries.get(0);
        }
      }
      StringBuilder msg = new StringBuilder();
      msg.append("More than one bean of type [");
      msg.append(clazz.getName());
      msg.append("] found, you have to specify the name of the bean ");
      msg.append(
          "(@SpringBean(name=\"foo\")) or (@Named(\"foo\") if using @javax.inject classes) in order to resolve this conflict. ");
      msg.append("Matched beans: ");
      msg.append(Strings.join(",", names.toArray(new String[names.size()])));
      throw new IllegalStateException(msg.toString());
    } else {
      return names.get(0);
    }
  }
  @SuppressWarnings("unchecked")
  public BeanDefinitionHolder decorate(
      Node node, BeanDefinitionHolder holder, ParserContext parserContext) {
    BeanDefinition filterChainProxy = holder.getBeanDefinition();

    ManagedList<BeanMetadataElement> securityFilterChains = new ManagedList<BeanMetadataElement>();
    Element elt = (Element) node;

    MatcherType matcherType = MatcherType.fromElement(elt);

    List<Element> filterChainElts = DomUtils.getChildElementsByTagName(elt, Elements.FILTER_CHAIN);

    for (Element chain : filterChainElts) {
      String path = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN);
      String filters = chain.getAttribute(HttpSecurityBeanDefinitionParser.ATT_FILTERS);

      if (!StringUtils.hasText(path)) {
        parserContext
            .getReaderContext()
            .error(
                "The attribute '"
                    + HttpSecurityBeanDefinitionParser.ATT_PATH_PATTERN
                    + "' must not be empty",
                elt);
      }

      if (!StringUtils.hasText(filters)) {
        parserContext
            .getReaderContext()
            .error(
                "The attribute '"
                    + HttpSecurityBeanDefinitionParser.ATT_FILTERS
                    + "'must not be empty",
                elt);
      }

      BeanDefinition matcher = matcherType.createMatcher(parserContext, path, null);

      if (filters.equals(HttpSecurityBeanDefinitionParser.OPT_FILTERS_NONE)) {
        securityFilterChains.add(createSecurityFilterChain(matcher, new ManagedList(0)));
      } else {
        String[] filterBeanNames = StringUtils.tokenizeToStringArray(filters, ",");
        ManagedList filterChain = new ManagedList(filterBeanNames.length);

        for (String name : filterBeanNames) {
          filterChain.add(new RuntimeBeanReference(name));
        }

        securityFilterChains.add(createSecurityFilterChain(matcher, filterChain));
      }
    }

    filterChainProxy.getConstructorArgumentValues().addGenericArgumentValue(securityFilterChains);

    return holder;
  }
  @Test
  public void eventBusElement() {
    BeanDefinition beanDefinition = beanFactory.getBeanDefinition("eventBus");
    assertNotNull("Bean definition not created", beanDefinition);
    assertEquals(
        "Wrong bean class", SimpleEventBus.class.getName(), beanDefinition.getBeanClassName());

    SimpleEventBus eventBus = beanFactory.getBean("eventBus", SimpleEventBus.class);
    assertNotNull(eventBus);
  }
 @Test
 public void servletWithCustomName() throws IOException {
   ScannedGenericBeanDefinition scanned =
       new ScannedGenericBeanDefinition(
           new SimpleMetadataReaderFactory().getMetadataReader(CustomNameServlet.class.getName()));
   this.handler.handle(scanned, this.registry);
   BeanDefinition servletRegistrationBean = this.registry.getBeanDefinition("custom");
   MutablePropertyValues propertyValues = servletRegistrationBean.getPropertyValues();
   assertThat(propertyValues.get("name")).isEqualTo("custom");
 }
예제 #22
0
  /**
   * Retrieves the configured property values for the view bean definition associated with the given
   * id
   *
   * <p>Since constructing the View object can be expensive, when metadata only is needed this
   * method can be used to retrieve the configured property values. Note this looks at the merged
   * bean definition
   *
   * @param viewId - id for the view to retrieve
   * @return PropertyValues configured on the view bean definition, or null if view is not found
   */
  public PropertyValues getViewPropertiesById(String viewId) {
    String beanName = viewBeanEntriesById.get(viewId);
    if (StringUtils.isNotBlank(beanName)) {
      BeanDefinition beanDefinition = ddBeans.getMergedBeanDefinition(beanName);

      return beanDefinition.getPropertyValues();
    }

    return null;
  }
  private void addKieBaseModels(
      ConfigurableListableBeanFactory beanFactory, KieModuleModelImpl kieModuleModel) {
    for (String beanDef : beanFactory.getBeanDefinitionNames()) {
      BeanDefinition beanDefinition = beanFactory.getBeanDefinition(beanDef);
      if (beanDefinition.getBeanClassName().equalsIgnoreCase(KBaseFactoryBean.class.getName())) {
        KieBaseModelImpl kBase = new KieBaseModelImpl();
        kBase.setKModule(kieModuleModel);

        kBase.setName(getPropertyValue(beanDefinition, "kBaseName"));
        kBase.setDefault("true".equals(getPropertyValue(beanDefinition, "def")));

        String packages = getPropertyValue(beanDefinition, "packages");
        if (!packages.isEmpty()) {
          for (String pkg : packages.split(",")) {
            kBase.addPackage(pkg.trim());
          }
        }

        String includes = getPropertyValue(beanDefinition, "includes");
        if (!includes.isEmpty()) {
          for (String include : includes.split(",")) {
            kBase.addInclude(include.trim());
          }
        }

        String eventMode = getPropertyValue(beanDefinition, "eventProcessingMode");
        if (!eventMode.isEmpty()) {
          kBase.setEventProcessingMode(
              EventProcessingOption.determineEventProcessingMode(eventMode));
        }

        String equalsBehavior = getPropertyValue(beanDefinition, "equalsBehavior");
        if (!equalsBehavior.isEmpty()) {
          kBase.setEqualsBehavior(EqualityBehaviorOption.determineEqualityBehavior(equalsBehavior));
        }

        String declarativeAgenda = getPropertyValue(beanDefinition, "declarativeAgenda");
        if (!declarativeAgenda.isEmpty()) {
          kBase.setDeclarativeAgenda(
              DeclarativeAgendaOption.determineDeclarativeAgenda(declarativeAgenda));
        }

        String scope = getPropertyValue(beanDefinition, "scope");
        if (!scope.isEmpty()) {
          kBase.setScope(scope.trim());
        }

        kieModuleModel.getRawKieBaseModels().put(kBase.getName(), kBase);
        beanDefinition
            .getPropertyValues()
            .addPropertyValue(new PropertyValue("releaseId", releaseId));
        addKieSessionModels(beanFactory, kBase);
      }
    }
  }
예제 #24
0
  @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;
  }
  public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
      throws BeanDefinitionStoreException {

    Assert.hasText(beanName, "Bean name must not be empty");
    Assert.notNull(beanDefinition, "Bean definition must not be null");

    if (beanDefinition instanceof AbstractBeanDefinition) {
      try {
        ((AbstractBeanDefinition) beanDefinition).validate();
      } catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(
            beanDefinition.getResourceDescription(),
            beanName,
            "Validation of bean definition failed",
            ex);
      }
    }

    Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
    if (oldBeanDefinition != null) {
      if (!this.allowBeanDefinitionOverriding) {
        throw new BeanDefinitionStoreException(
            beanDefinition.getResourceDescription(),
            beanName,
            "Cannot register bean definition ["
                + beanDefinition
                + "] for bean '"
                + beanName
                + "': there's already ["
                + oldBeanDefinition
                + "] bound");
      } else {
        if (logger.isInfoEnabled()) {
          logger.info(
              "Overriding bean definition for bean '"
                  + beanName
                  + "': replacing ["
                  + oldBeanDefinition
                  + "] with ["
                  + beanDefinition
                  + "]");
        }
      }
    } else {
      this.beanDefinitionNames.add(beanName);
    }
    this.beanDefinitionMap.put(beanName, beanDefinition);

    // Remove corresponding bean from singleton cache, if any.
    // Shouldn't usually be necessary, rather just meant for overriding
    // a context's default beans (e.g. the default StaticMessageSource
    // in a StaticApplicationContext).
    removeSingleton(beanName);
  }
예제 #26
0
 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory factory)
     throws BeansException {
   System.out.println("postProcessBeanFactory接口被调用");
   BeanDefinition bean = factory.getBeanDefinition("MyBean");
   // 拿到这个bean的所有属性
   MutablePropertyValues pv = bean.getPropertyValues();
   if (pv.contains("name")) {
     pv.addPropertyValue("name", "被修改了");
   }
 }
 /**
  * Determines if the {@code dataSource} being used by Spring was created from {@link
  * EmbeddedDataSourceConfiguration}.
  *
  * @param beanFactory the bean factory
  * @return true if the data source was auto-configured.
  */
 public static boolean containsAutoConfiguredDataSource(
     ConfigurableListableBeanFactory beanFactory) {
   try {
     BeanDefinition beanDefinition = beanFactory.getBeanDefinition("dataSource");
     return EmbeddedDataSourceConfiguration.class
         .getName()
         .equals(beanDefinition.getFactoryBeanName());
   } catch (NoSuchBeanDefinitionException ex) {
     return false;
   }
 }
  /** @see DATAMONGO-1218 */
  @Test
  public void setsUpMongoDbFactoryUsingAMongoClientUri() {

    reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-client-uri.xml"));
    BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
    ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();

    assertThat(constructorArguments.getArgumentCount(), is(1));
    ValueHolder argument = constructorArguments.getArgumentValue(0, MongoClientURI.class);
    assertThat(argument, is(notNullValue()));
  }
    public final List<Class<?>> getComponentClasses(String basePackage) {
      List<Class<?>> classes = new ArrayList<Class<?>>();

      for (BeanDefinition candidate : findCandidateComponents(basePackage)) {
        Class<?> cls =
            ClassUtils.resolveClassName(
                candidate.getBeanClassName(), ClassUtils.getDefaultClassLoader());

        classes.add(cls);
      }
      return classes;
    }
 /** {@inheritDoc} */
 public void postProcess(
     BundleContext bundleContext, ConfigurableListableBeanFactory beanFactory) {
   String[] beanDefinitionNames = beanFactory.getBeanDefinitionNames();
   for (String name : beanDefinitionNames) {
     BeanDefinition beanDefinition = beanFactory.getBeanDefinition(name);
     if (isServiceImportDefinition(beanDefinition)) {
       MutablePropertyValues propertyValues = beanDefinition.getPropertyValues();
       propertyValues.addPropertyValue(
           PROPERTY_CONTEXT_CLASS_LOADER, ImportContextClassLoaderEnum.UNMANAGED);
     }
   }
 }