protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
    AnnotationMetadata metadata = configClass.getMetadata();
    if (this.environment != null && ProfileHelper.isProfileAnnotationPresent(metadata)) {
      if (!this.environment.acceptsProfiles(ProfileHelper.getCandidateProfiles(metadata))) {
        return;
      }
    }

    while (metadata != null) {
      doProcessConfigurationClass(configClass, metadata);
      String superClassName = metadata.getSuperClassName();
      if (superClassName != null && !Object.class.getName().equals(superClassName)) {
        if (metadata instanceof StandardAnnotationMetadata) {
          Class<?> clazz = ((StandardAnnotationMetadata) metadata).getIntrospectedClass();
          metadata = new StandardAnnotationMetadata(clazz.getSuperclass());
        } else {
          MetadataReader reader = this.metadataReaderFactory.getMetadataReader(superClassName);
          metadata = reader.getAnnotationMetadata();
        }
      } else {
        metadata = null;
      }
    }
    if (this.configurationClasses.contains(configClass) && configClass.getBeanName() != null) {
      // Explicit bean definition found, probably replacing an import.
      // Let's remove the old one and go with the new one.
      this.configurationClasses.remove(configClass);
    }

    this.configurationClasses.add(configClass);
  }
 /**
  * Perform Spring-based scanning for entity classes, registering them as annotated classes with
  * this {@code Configuration}.
  *
  * @param packagesToScan one or more Java package names
  * @throws HibernateException if scanning fails for any reason
  */
 public void scanPackages(String... packagesToScan) throws HibernateException {
   try {
     for (String pkg : packagesToScan) {
       String pattern =
           ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
               + ClassUtils.convertClassNameToResourcePath(pkg)
               + RESOURCE_PATTERN;
       Resource[] resources = resourcePatternResolver.getResources(pattern);
       MetadataReaderFactory readerFactory =
           new CachingMetadataReaderFactory(resourcePatternResolver);
       for (Resource resource : resources) {
         if (resource.isReadable()) {
           MetadataReader reader = readerFactory.getMetadataReader(resource);
           String className = reader.getClassMetadata().getClassName();
           if (matchesFilter(reader, readerFactory)) {
             addAnnotatedClasses(resourcePatternResolver.getClassLoader().loadClass(className));
           }
         }
       }
     }
   } catch (IOException ex) {
     throw new MappingException("Failed to scan classpath for unlisted classes", ex);
   } catch (ClassNotFoundException ex) {
     throw new MappingException("Failed to load annotated classes from classpath", ex);
   }
 }
 /**
  * Perform Spring-based scanning for entity classes.
  *
  * @see #setPackagesToScan
  */
 private SpringPersistenceUnitInfo buildDefaultPersistenceUnitInfo() {
   SpringPersistenceUnitInfo scannedUnit = new SpringPersistenceUnitInfo();
   scannedUnit.setPersistenceUnitName(this.defaultPersistenceUnitName);
   scannedUnit.excludeUnlistedClasses();
   if (this.packagesToScan != null) {
     for (String pkg : this.packagesToScan) {
       try {
         String pattern =
             ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                 + ClassUtils.convertClassNameToResourcePath(pkg)
                 + ENTITY_CLASS_RESOURCE_PATTERN;
         Resource[] resources = this.resourcePatternResolver.getResources(pattern);
         MetadataReaderFactory readerFactory =
             new CachingMetadataReaderFactory(this.resourcePatternResolver);
         for (Resource resource : resources) {
           if (resource.isReadable()) {
             MetadataReader reader = readerFactory.getMetadataReader(resource);
             String className = reader.getClassMetadata().getClassName();
             if (matchesFilter(reader, readerFactory)) {
               scannedUnit.addManagedClassName(className);
             }
           }
         }
       } catch (IOException ex) {
         throw new PersistenceException("Failed to scan classpath for unlisted classes", ex);
       }
     }
   }
   if (this.mappingResources != null) {
     for (String mappingFileName : this.mappingResources) {
       scannedUnit.addMappingFileName(mappingFileName);
     }
   }
   return scannedUnit;
 }
Beispiel #4
0
  public Set<Class> doScan(String basePackage) {
    Set<Class> classes = new HashSet<Class>();
    try {
      String packageSearchPath =
          ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
              + ClassUtils.convertClassNameToResourcePath(
                  SystemPropertyUtils.resolvePlaceholders(basePackage))
              + DEFAULT_RESOURCE_PATTERN;
      Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath);

      for (int i = 0; i < resources.length; i++) {
        Resource resource = resources[i];
        if (resource.isReadable()) {
          MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource);
          if ((includeFilters.size() == 0 && excludeFilters.size() == 0)
              || matches(metadataReader)) {
            try {
              classes.add(Class.forName(metadataReader.getClassMetadata().getClassName()));
            } catch (ClassNotFoundException e) {
              e.printStackTrace();
            }
          }
        }
      }
    } catch (IOException ex) {
      throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
    }
    return classes;
  }
  /** 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);
      }
    }
  }
 private void processFeatureAnnotations(AnnotationMetadata metadata) {
   try {
     for (String annotationType : metadata.getAnnotationTypes()) {
       MetadataReader metadataReader =
           new SimpleMetadataReaderFactory().getMetadataReader(annotationType);
       if (metadataReader.getAnnotationMetadata().isAnnotated(FeatureAnnotation.class.getName())) {
         Map<String, Object> annotationAttributes =
             metadataReader
                 .getAnnotationMetadata()
                 .getAnnotationAttributes(FeatureAnnotation.class.getName(), true);
         // TODO SPR-7420: this is where we can catch user-defined types and avoid instantiating
         // them for STS purposes
         FeatureAnnotationParser processor =
             (FeatureAnnotationParser)
                 BeanUtils.instantiateClass(
                     Class.forName((String) annotationAttributes.get("parser")));
         FeatureSpecification spec = processor.process(metadata);
         spec.execute(this.specificationContext);
       }
     }
   } catch (BeanDefinitionParsingException ex) {
     throw ex;
   } catch (Exception ex) {
     // TODO SPR-7420: what exception to throw?
     throw new RuntimeException(ex);
   }
 }
Beispiel #7
0
 /** method adds all the method names to map with annotation attribute value as key */
 private static void findAnnotationMethods(
     final Class<? extends Annotation> annotationClass, final String attributeName)
     throws IOException {
   final String basePackagePath =
       ClassUtils.convertClassNameToResourcePath(
           new StandardEnvironment().resolveRequiredPlaceholders(SEARCH_PACKAGE));
   final String packageSearchPath =
       ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + basePackagePath + "/" + RESOURCE_PATTERN;
   final Resource[] resources = resourcePatternResolver.getResources(packageSearchPath);
   for (final Resource resource : resources) {
     if (resource.isReadable()) {
       final MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(resource);
       final Set<MethodMetadata> metadataSet =
           metadataReader.getAnnotationMetadata().getAnnotatedMethods(annotationClass.getName());
       if (metadataSet != null && metadataSet.size() > 0) {
         for (final MethodMetadata metadata : metadataSet) {
           final Map<String, Object> attributes =
               metadata.getAnnotationAttributes(annotationClass.getName());
           final JobName attributeValue = (JobName) attributes.get(attributeName);
           final String className = metadata.getDeclaringClassName();
           final String[] mapVal = {className, metadata.getMethodName()};
           targetMethosMap.put(attributeValue.toString(), mapVal);
         }
       }
     }
   }
 }
 @Test
 public void asmAnnotationMetadataForSubclass() throws Exception {
   MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
   MetadataReader metadataReader =
       metadataReaderFactory.getMetadataReader(AnnotatedComponentSubClass.class.getName());
   AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
   doTestSubClassAnnotationInfo(metadata);
 }
 @Test
 public void asmAnnotationMetadataForAnnotation() throws Exception {
   MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
   MetadataReader metadataReader =
       metadataReaderFactory.getMetadataReader(Component.class.getName());
   AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
   doTestMetadataForAnnotationClass(metadata);
 }
 @Test
 public void metaAnnotationOverridesUsingAnnotationMetadataReadingVisitor() throws Exception {
   MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
   MetadataReader metadataReader =
       metadataReaderFactory.getMetadataReader(
           ComposedConfigurationWithAttributeOverridesClass.class.getName());
   AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
   assertMetaAnnotationOverrides(metadata);
 }
 /** https://jira.spring.io/browse/SPR-11649 */
 @Test
 public void multipleAnnotationsWithIdenticalAttributeNamesUsingAnnotationMetadataReadingVisitor()
     throws Exception {
   MetadataReaderFactory metadataReaderFactory = new SimpleMetadataReaderFactory();
   MetadataReader metadataReader =
       metadataReaderFactory.getMetadataReader(NamedAnnotationsClass.class.getName());
   AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
   assertMultipleAnnotationsWithIdenticalAttributeNames(metadata);
 }
  @Test
  public void testSubtypeOfGenericSupertype() throws Exception {
    MetadataReader metadataReader = factory.getMetadataReader("org.test.spring.GenericSubtype");

    ClassMetadata metadata = metadataReader.getClassMetadata();
    assertEquals("org.test.spring.GenericSubtype", metadata.getClassName());
    assertEquals(0, metadata.getInterfaceNames().length);

    assertFalse(metadata.hasEnclosingClass());
    assertNull(metadata.getEnclosingClassName());

    assertTrue(metadata.hasSuperClass());
    assertEquals("org.test.spring.GenericSupertype", metadata.getSuperClassName());
  }
  @Test
  public void testPlainInterface() throws Exception {
    MetadataReader metadataReader = factory.getMetadataReader("org.test.spring.PlainInterface");

    ClassMetadata metadata = metadataReader.getClassMetadata();
    assertEquals("org.test.spring.PlainInterface", metadata.getClassName());
    assertEquals(0, metadata.getInterfaceNames().length);

    assertFalse(metadata.hasEnclosingClass());
    assertNull(metadata.getEnclosingClassName());

    assertTrue(metadata.hasSuperClass());
    assertEquals("java.lang.Object", metadata.getSuperClassName());
  }
 /**
  * Perform Spring-based scanning for entity classes, registering them as annotated classes with
  * this {@code Configuration}.
  *
  * @param packagesToScan one or more Java package names
  * @throws HibernateException if scanning fails for any reason
  */
 public LocalSessionFactoryBuilder scanPackages(String... packagesToScan)
     throws HibernateException {
   Set<String> entityClassNames = new TreeSet<String>();
   Set<String> converterClassNames = new TreeSet<String>();
   Set<String> packageNames = new TreeSet<String>();
   try {
     for (String pkg : packagesToScan) {
       String pattern =
           ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
               + ClassUtils.convertClassNameToResourcePath(pkg)
               + RESOURCE_PATTERN;
       Resource[] resources = this.resourcePatternResolver.getResources(pattern);
       MetadataReaderFactory readerFactory =
           new CachingMetadataReaderFactory(this.resourcePatternResolver);
       for (Resource resource : resources) {
         if (resource.isReadable()) {
           MetadataReader reader = readerFactory.getMetadataReader(resource);
           String className = reader.getClassMetadata().getClassName();
           if (matchesEntityTypeFilter(reader, readerFactory)) {
             entityClassNames.add(className);
           } else if (converterTypeFilter != null
               && converterTypeFilter.match(reader, readerFactory)) {
             converterClassNames.add(className);
           } else if (className.endsWith(PACKAGE_INFO_SUFFIX)) {
             packageNames.add(
                 className.substring(0, className.length() - PACKAGE_INFO_SUFFIX.length()));
           }
         }
       }
     }
   } catch (IOException ex) {
     throw new MappingException("Failed to scan classpath for unlisted classes", ex);
   }
   try {
     ClassLoader cl = this.resourcePatternResolver.getClassLoader();
     for (String className : entityClassNames) {
       addAnnotatedClass(cl.loadClass(className));
     }
     for (String className : converterClassNames) {
       ConverterRegistrationDelegate.registerConverter(this, cl.loadClass(className));
     }
     for (String packageName : packageNames) {
       addPackage(packageName);
     }
   } catch (ClassNotFoundException ex) {
     throw new MappingException("Failed to load annotated classes from classpath", ex);
   }
   return this;
 }
  @Test
  public void testSubClassOfBinaryType() throws Exception {
    MetadataReader metadataReader =
        factory.getMetadataReader("org.test.spring.SubClassOfBinaryType");

    ClassMetadata metadata = metadataReader.getClassMetadata();
    assertEquals("org.test.spring.SubClassOfBinaryType", metadata.getClassName());
    assertEquals(0, metadata.getInterfaceNames().length);

    assertFalse(metadata.hasEnclosingClass());
    assertNull(metadata.getEnclosingClassName());

    assertTrue(metadata.hasSuperClass());
    assertEquals("org.springframework.core.SpringVersion", metadata.getSuperClassName());
  }
  @Test
  public void testSubClass() throws Exception {
    MetadataReader metadataReader =
        factory.getMetadataReader("org.test.spring.SubClassWithoutAnnotation");

    ClassMetadata metadata = metadataReader.getClassMetadata();
    assertEquals("org.test.spring.SubClassWithoutAnnotation", metadata.getClassName());
    assertEquals(0, metadata.getInterfaceNames().length);

    assertFalse(metadata.hasEnclosingClass());
    assertNull(metadata.getEnclosingClassName());

    assertTrue(metadata.hasSuperClass());
    assertEquals("org.test.spring.SimpleConfigurationClass", metadata.getSuperClassName());
  }
  @Test
  public void testSimpleClass() throws Exception {
    MetadataReader metadataReader = factory.getMetadataReader("org.test.spring.NoAnnotations");

    ClassMetadata metadata = metadataReader.getClassMetadata();
    assertEquals("org.test.spring.NoAnnotations", metadata.getClassName());
    assertEquals(0, metadata.getInterfaceNames().length);

    assertFalse(metadata.hasEnclosingClass());
    assertNull(metadata.getEnclosingClassName());

    assertTrue(metadata.hasSuperClass());
    assertEquals("java.lang.Object", metadata.getSuperClassName());

    assertTrue(metadata instanceof JdtConnectedMetadata);
    IType type = JdtUtils.getJavaType(project, "org.test.spring.NoAnnotations");
    assertEquals(type, ((JdtConnectedMetadata) metadata).getJavaElement());
  }
 private Class<?> loadClass(
     ClassLoader loader, MetadataReaderFactory readerFactory, Resource resource) {
   try {
     MetadataReader reader = readerFactory.getMetadataReader(resource);
     return ClassUtils.forName(reader.getClassMetadata().getClassName(), loader);
   } catch (ClassNotFoundException ex) {
     handleFailure(resource, ex);
     return null;
   } catch (LinkageError ex) {
     handleFailure(resource, ex);
     return null;
   } catch (Throwable ex) {
     if (this.logger.isWarnEnabled()) {
       this.logger.warn("Unexpected failure when loading class resource " + resource, ex);
     }
     return null;
   }
 }
    public Collection<SourceClass> getMemberClasses() throws IOException {
      Object sourceToProcess = this.source;
      if (sourceToProcess instanceof Class<?>) {
        Class<?> sourceClass = (Class<?>) sourceToProcess;
        try {
          Class<?>[] declaredClasses = sourceClass.getDeclaredClasses();
          List<SourceClass> members = new ArrayList<SourceClass>(declaredClasses.length);
          for (Class<?> declaredClass : declaredClasses) {
            members.add(asSourceClass(declaredClass));
          }
          return members;
        } catch (NoClassDefFoundError err) {
          // getDeclaredClasses() failed because of non-resolvable dependencies
          // -> fall back to ASM below
          sourceToProcess = metadataReaderFactory.getMetadataReader(sourceClass.getName());
        }
      }

      // ASM-based resolution - safe for non-resolvable classes as well
      MetadataReader sourceReader = (MetadataReader) sourceToProcess;
      String[] memberClassNames = sourceReader.getClassMetadata().getMemberClassNames();
      List<SourceClass> members = new ArrayList<SourceClass>(memberClassNames.length);
      for (String memberClassName : memberClassNames) {
        try {
          members.add(asSourceClass(memberClassName));
        } catch (IOException ex) {
          // Let's skip it if it's not resolvable - we're just looking for candidates
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Failed to resolve member class ["
                    + memberClassName
                    + "] - not considering it as a configuration class candidate");
          }
        }
      }
      return members;
    }
  /**
   * Check whether the given bean definition is a candidate for a configuration class, and mark it
   * accordingly.
   *
   * @param beanDef the bean definition to check
   * @param metadataReaderFactory the current factory in use by the caller
   * @return whether the candidate qualifies as (any kind of) configuration class
   */
  public static boolean checkConfigurationClassCandidate(
      BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
    AnnotationMetadata metadata = null;

    // Check already loaded Class if present...
    // since we possibly can't even load the class file for this Class.
    if (beanDef instanceof AbstractBeanDefinition
        && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
      metadata = new StandardAnnotationMetadata(((AbstractBeanDefinition) beanDef).getBeanClass());
    } else {
      String className = beanDef.getBeanClassName();
      if (className != null) {
        try {
          MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
          metadata = metadataReader.getAnnotationMetadata();
        } catch (IOException ex) {
          if (logger.isDebugEnabled()) {
            logger.debug(
                "Could not find class file for introspecting factory methods: " + className, ex);
          }
          return false;
        }
      }
    }

    if (metadata != null) {
      if (metadata.isAnnotated(Configuration.class.getName())) {
        beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
        return true;
      } else if (metadata.isAnnotated(Component.class.getName())
          || metadata.hasAnnotatedMethods(Bean.class.getName())) {
        beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
        return true;
      }
    }
    return false;
  }
 /**
  * Determine whether the given class does not match any exclude filter and does match at least one
  * include filter.
  *
  * @param metadataReader the ASM ClassReader for the class
  * @return whether the class qualifies as a candidate component
  */
 protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
   for (TypeFilter tf : this.excludeFilters) {
     if (tf.match(metadataReader, this.metadataReaderFactory)) {
       return false;
     }
   }
   for (TypeFilter tf : this.includeFilters) {
     if (tf.match(metadataReader, this.metadataReaderFactory)) {
       AnnotationMetadata metadata = metadataReader.getAnnotationMetadata();
       if (!metadata.isAnnotated(Profile.class.getName())) {
         return true;
       }
       AnnotationAttributes profile = MetadataUtils.attributesFor(metadata, Profile.class);
       return this.environment.acceptsProfiles(profile.getStringArray("value"));
     }
   }
   return false;
 }
  protected void doProcessConfigurationClass(
      ConfigurationClass configClass, AnnotationMetadata metadata) throws IOException {

    // recursively process any member (nested) classes first
    for (String memberClassName : metadata.getMemberClassNames()) {
      MetadataReader reader = this.metadataReaderFactory.getMetadataReader(memberClassName);
      AnnotationMetadata memberClassMetadata = reader.getAnnotationMetadata();
      if (isConfigurationCandidate(memberClassMetadata)) {
        processConfigurationClass(new ConfigurationClass(reader, null));
      }
    }

    // process any @PropertySource annotations
    Map<String, Object> propertySourceAttributes =
        metadata.getAnnotationAttributes(
            org.springframework.context.annotation.PropertySource.class.getName());
    if (propertySourceAttributes != null) {
      String name = (String) propertySourceAttributes.get("name");
      String[] locations = (String[]) propertySourceAttributes.get("value");
      ClassLoader classLoader = this.resourceLoader.getClassLoader();
      for (String location : locations) {
        location = this.environment.resolveRequiredPlaceholders(location);
        ResourcePropertySource ps =
            StringUtils.hasText(name)
                ? new ResourcePropertySource(name, location, classLoader)
                : new ResourcePropertySource(location, classLoader);
        this.propertySources.push(ps);
      }
    }

    // process any @ComponentScan annotions
    Map<String, Object> componentScanAttributes =
        metadata.getAnnotationAttributes(ComponentScan.class.getName());
    if (componentScanAttributes != null) {
      // the config class is annotated with @ComponentScan -> perform the scan immediately
      Set<BeanDefinitionHolder> scannedBeanDefinitions =
          this.componentScanParser.parse(componentScanAttributes);

      // check the set of scanned definitions for any further config classes and parse recursively
      // if necessary
      for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
        if (ConfigurationClassUtils.checkConfigurationClassCandidate(
            holder.getBeanDefinition(), metadataReaderFactory)) {
          try {
            this.parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
          } catch (ConflictingBeanDefinitionException ex) {
            throw new CircularComponentScanException(
                "A conflicting bean definition was detected while processing @ComponentScan annotations. "
                    + "This usually indicates a circle between scanned packages.",
                ex);
          }
        }
      }
    }

    // process any @Import annotations
    List<Map<String, Object>> allImportAttribs =
        AnnotationUtils.findAllAnnotationAttributes(Import.class, metadata.getClassName(), true);
    for (Map<String, Object> importAttribs : allImportAttribs) {
      processImport(configClass, (String[]) importAttribs.get("value"), true);
    }

    // process any @ImportResource annotations
    if (metadata.isAnnotated(ImportResource.class.getName())) {
      String[] resources =
          (String[]) metadata.getAnnotationAttributes(ImportResource.class.getName()).get("value");
      Class<?> readerClass =
          (Class<?>) metadata.getAnnotationAttributes(ImportResource.class.getName()).get("reader");
      if (readerClass == null) {
        throw new IllegalStateException(
            "No reader class associated with imported resources: "
                + StringUtils.arrayToCommaDelimitedString(resources));
      }
      for (String resource : resources) {
        configClass.addImportedResource(resource, readerClass);
      }
    }

    // process individual @Bean methods
    Set<MethodMetadata> beanMethods = metadata.getAnnotatedMethods(Bean.class.getName());
    for (MethodMetadata methodMetadata : beanMethods) {
      configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
    }
  }
  public static void main(String[] args) throws Exception {
    try {
      ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();

      AnnotationConfiguration config =
          new AnnotationConfiguration()
              .configure(new File("D:/gjxt/source/news/config/hibernate/hibernate.cfg.xml"));
      config.setProperty("output", "C:\\ddl.txt");

      String[] packagesToScan = {"com.team.cmc.domain.model"};
      for (String pkg : packagesToScan) {
        String pattern =
            ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
                + ClassUtils.convertClassNameToResourcePath(pkg)
                + "/**/*.class";
        Resource[] resources = resourcePatternResolver.getResources(pattern);
        MetadataReaderFactory readerFactory =
            new CachingMetadataReaderFactory(resourcePatternResolver);
        for (Resource resource : resources) {
          if (resource.isReadable()) {
            MetadataReader reader = readerFactory.getMetadataReader(resource);
            String className = reader.getClassMetadata().getClassName();
            if (matchesFilter(reader, readerFactory)) {
              config.addAnnotatedClass(
                  resourcePatternResolver.getClassLoader().loadClass(className));
            }
          }
        }
      }

      SessionFactory sessionFactory = config.buildSessionFactory();
      session = sessionFactory.openSession();
      tx = session.beginTransaction();

      SchemaExport schemaExport = new SchemaExport(config);
      schemaExport.setOutputFile("c:\\a.txt");
      schemaExport.create(true, true);

      System.out.println("Table created.");

      tx.commit();

      //
      // config = new Configuration().configure(new File(
      // "src/hibernate.cfg.xml"));
      //
      // System.out.println("Creating tables...");
      //
      // SessionFactory sessionFactory = config.configure()
      // .buildSessionFactory();
      // session = sessionFactory.openSession();
      // tx = session.beginTransaction();
      //
      // SchemaExport schemaExport = new SchemaExport(config);
      // schemaExport.create(true, true);
      //
      // System.out.println("Table created.");
      //
      // tx.commit();

    } catch (HibernateException e) {
      e.printStackTrace();
      try {
        tx.rollback();
      } catch (HibernateException e1) {
        e1.printStackTrace();
      }
    } finally {

    }
  }
 /**
  * @author:shaochuan.wangsc
  * @date:2010-3-24
  */
 private void scan(WebModuleConfigurer webModuleConfigurer) {
   try {
     String pattern =
         ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX
             + ClassUtils.convertClassNameToResourcePath(
                 webModuleConfigurer.getModuleBasePackage())
             + webModuleConfigurer.getContextPackage()
             + RESOURCE_PATTERN;
     Resource[] resources = this.resourcePatternResolver.getResources(pattern);
     MetadataReaderFactory readerFactory =
         new CachingMetadataReaderFactory(this.resourcePatternResolver);
     //
     for (Resource resource : resources) {
       if (resource.isReadable()) {
         MetadataReader reader = readerFactory.getMetadataReader(resource);
         ClassMetadata classMetadata = reader.getClassMetadata();
         //
         if (classMetadata.isConcrete()) {
           String className = classMetadata.getClassName();
           if (!(BeanUtils.isWidget(className) || BeanUtils.isController(className))) {
             continue;
           }
           //
           AutowireCapableBeanFactory beanFactory =
               applicationContext.getAutowireCapableBeanFactory();
           Object clazz =
               beanFactory.createBean(
                   classLoader.loadClass(className),
                   AutowireCapableBeanFactory.AUTOWIRE_NO,
                   false);
           //
           if (clazz instanceof FreeMarkerWidget) {
             String widget = className.replace(webModuleConfigurer.getModuleBasePackage(), "");
             widget = ClassUtils.convertClassNameToResourcePath(widget);
             widget = BeanUtils.stripEndString(widget, BeanUtils.WIDGET_BEAN_SUFFIX);
             String widgetKey = BeanUtils.makeControllerOrWidgetMappingKey(widget);
             webModuleConfigurer.getWidgetMap().put(widgetKey, (FreeMarkerWidget) clazz);
             widgets.put(widgetKey, (FreeMarkerWidget) clazz);
           }
           //
           if (clazz instanceof Controller) {
             String controller = className.replace(webModuleConfigurer.getModuleBasePackage(), "");
             controller = ClassUtils.convertClassNameToResourcePath(controller);
             controller = BeanUtils.stripEndString(controller, BeanUtils.CONTROLLER_BEAN_SUFFIX);
             String controllerKey = BeanUtils.makeControllerOrWidgetMappingKey(controller);
             String controllerRule =
                 webModuleConfigurer.getContextPackage() + CONTROLLERS_PACKAGE + SLASH;
             if (controllerKey.startsWith(controllerRule)) {
               //
               controllerKey =
                   controllerKey.replaceFirst(controllerRule, webModuleConfigurer.getContext());
               //
               if ("/index".equals(controllerKey)) {
                 webModuleConfigurer.getControllerMap().put("/", (Controller) clazz);
                 controllers.put("/", (Controller) clazz);
                 defaultListableBeanFactory.registerSingleton("/", (Controller) clazz);
               }
               //
               String controller_key = BeanUtils.processControllerKey(controllerKey);
               String controller_keyv = controller_key + webModuleConfigurer.getUriExtension();
               //
               webModuleConfigurer.getControllerMap().put(controller_keyv, (Controller) clazz);
               controllers.put(controller_keyv, (Controller) clazz);
               defaultListableBeanFactory.registerSingleton(controller_keyv, (Controller) clazz);
             }
           }
         }
       }
     }
   } catch (IOException e) {
     logger.error("Failed to scan classpath for unlisted classes", e);
     throw new RuntimeException("Failed to scan classpath for unlisted classes", e);
   } catch (ClassNotFoundException e) {
     logger.error("Failed to load classes from classpath", e);
     throw new RuntimeException("Failed to load classes from classpath", e);
   }
 }
 @Override
 public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException {
   ComponentScan cs = TestConfiguration.class.getAnnotation(ComponentScan.class);
   return SpringUtils.includedInBasePackageClasses(mdr.getClassMetadata().getClassName(), cs);
 }
 @Override
 public boolean match(MetadataReader mdr, MetadataReaderFactory arg1) throws IOException {
   String clsname = mdr.getClassMetadata().getClassName();
   ComponentScan cs = IntegrationTestConfiguration.class.getAnnotation(ComponentScan.class);
   return includedInBasePackageClasses(clsname, cs);
 }