List of usage examples for org.springframework.beans BeanUtils instantiateClass
public static <T> T instantiateClass(Constructor<T> ctor, Object... args) throws BeanInstantiationException
From source file:org.springframework.context.annotation.ConfigurationClassParser.java
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass, Collection<SourceClass> importCandidates, boolean checkForCircularImports) throws IOException { if (importCandidates.isEmpty()) { return;//w w w . j a v a 2 s . c om } if (checkForCircularImports && isChainedImportOnStack(configClass)) { this.problemReporter.error(new CircularImportProblem(configClass, this.importStack)); } else { this.importStack.push(configClass); try { for (SourceClass candidate : importCandidates) { if (candidate.isAssignable(ImportSelector.class)) { // Candidate class is an ImportSelector -> delegate to it to determine imports Class<?> candidateClass = candidate.loadClass(); ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class); ParserStrategyUtils.invokeAwareMethods(selector, this.environment, this.resourceLoader, this.registry); if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) { this.deferredImportSelectors.add(new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector)); } else { String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata()); Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames); processImports(configClass, currentSourceClass, importSourceClasses, false); } } else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) { // Candidate class is an ImportBeanDefinitionRegistrar -> // delegate to it to register additional bean definitions Class<?> candidateClass = candidate.loadClass(); ImportBeanDefinitionRegistrar registrar = BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class); ParserStrategyUtils.invokeAwareMethods(registrar, this.environment, this.resourceLoader, this.registry); configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata()); } else { // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar -> // process it as an @Configuration class this.importStack.registerImport(currentSourceClass.getMetadata(), candidate.getMetadata().getClassName()); processConfigurationClass(candidate.asConfigClass(configClass)); } } } catch (BeanDefinitionStoreException ex) { throw ex; } catch (Throwable ex) { throw new BeanDefinitionStoreException( "Failed to process import candidates for configuration class [" + configClass.getMetadata().getClassName() + "]", ex); } finally { this.importStack.pop(); } } }
From source file:org.springframework.security.oauth2.client.test.OAuth2ContextSetup.java
private OAuth2ProtectedResourceDetails creatResource(Object target, OAuth2ContextConfiguration contextLoader) { Class<? extends OAuth2ProtectedResourceDetails> type = contextLoader.value(); if (type == OAuth2ProtectedResourceDetails.class) { type = contextLoader.resource(); }//from ww w. j av a 2s . co m Constructor<? extends OAuth2ProtectedResourceDetails> constructor = ClassUtils .getConstructorIfAvailable(type, TestAccounts.class); if (constructor != null && testAccounts != null) { return BeanUtils.instantiateClass(constructor, testAccounts); } constructor = ClassUtils.getConstructorIfAvailable(type, Environment.class); if (constructor != null && environment != null) { return BeanUtils.instantiateClass(constructor, environment); } constructor = ClassUtils.getConstructorIfAvailable(type, Object.class); if (constructor != null) { return BeanUtils.instantiateClass(constructor, target); } // Fallback to default constructor return BeanUtils.instantiate(type); }
From source file:org.springframework.test.context.BootstrapUtils.java
@SuppressWarnings("unchecked") private static CacheAwareContextLoaderDelegate createCacheAwareContextLoaderDelegate() { Class<? extends CacheAwareContextLoaderDelegate> clazz = null; try {// w w w . j a v a2 s . c om clazz = (Class<? extends CacheAwareContextLoaderDelegate>) ClassUtils.forName( DEFAULT_CACHE_AWARE_CONTEXT_LOADER_DELEGATE_CLASS_NAME, BootstrapUtils.class.getClassLoader()); if (logger.isDebugEnabled()) { logger.debug(String.format("Instantiating CacheAwareContextLoaderDelegate from class [%s]", clazz.getName())); } return BeanUtils.instantiateClass(clazz, CacheAwareContextLoaderDelegate.class); } catch (Throwable ex) { throw new IllegalStateException("Could not load CacheAwareContextLoaderDelegate [" + clazz + "]", ex); } }
From source file:org.springframework.test.context.BootstrapUtils.java
/** * Resolve the {@link TestContextBootstrapper} type for the test class in the * supplied {@link BootstrapContext}, instantiate it, and provide it a reference * to the {@link BootstrapContext}./* w w w . ja v a 2 s . co m*/ * <p>If the {@link BootstrapWith @BootstrapWith} annotation is present on * the test class, either directly or as a meta-annotation, then its * {@link BootstrapWith#value value} will be used as the bootstrapper type. * Otherwise, either the * {@link org.springframework.test.context.support.DefaultTestContextBootstrapper * DefaultTestContextBootstrapper} or the * {@link org.springframework.test.context.web.WebTestContextBootstrapper * WebTestContextBootstrapper} will be used, depending on the presence of * {@link org.springframework.test.context.web.WebAppConfiguration @WebAppConfiguration}. * @param bootstrapContext the bootstrap context to use * @return a fully configured {@code TestContextBootstrapper} */ static TestContextBootstrapper resolveTestContextBootstrapper(BootstrapContext bootstrapContext) { Class<?> testClass = bootstrapContext.getTestClass(); Class<?> clazz = null; try { clazz = resolveExplicitTestContextBootstrapper(testClass); if (clazz == null) { clazz = resolveDefaultTestContextBootstrapper(testClass); } if (logger.isDebugEnabled()) { logger.debug( String.format("Instantiating TestContextBootstrapper for test class [%s] from class [%s]", testClass.getName(), clazz.getName())); } TestContextBootstrapper testContextBootstrapper = BeanUtils.instantiateClass(clazz, TestContextBootstrapper.class); testContextBootstrapper.setBootstrapContext(bootstrapContext); return testContextBootstrapper; } catch (IllegalStateException ex) { throw ex; } catch (Throwable ex) { throw new IllegalStateException("Could not load TestContextBootstrapper [" + clazz + "]. Specify @BootstrapWith's 'value' attribute or make the default bootstrapper class available.", ex); } }
From source file:org.springframework.test.context.support.AbstractTestContextBootstrapper.java
/** * Resolve the {@link ContextLoader} {@linkplain Class class} to use for the * supplied list of {@link ContextConfigurationAttributes} and then instantiate * and return that {@code ContextLoader}. * <p>If the user has not explicitly declared which loader to use, the value * returned from {@link #getDefaultContextLoaderClass} will be used as the * default context loader class. For details on the class resolution process, * see {@link #resolveExplicitContextLoaderClass} and * {@link #getDefaultContextLoaderClass}. * @param testClass the test class for which the {@code ContextLoader} should be * resolved; must not be {@code null}/*from w ww .j a va 2 s. c om*/ * @param configAttributesList the list of configuration attributes to process; must * not be {@code null}; must be ordered <em>bottom-up</em> * (i.e., as if we were traversing up the class hierarchy) * @return the resolved {@code ContextLoader} for the supplied {@code testClass} * (never {@code null}) * @throws IllegalStateException if {@link #getDefaultContextLoaderClass(Class)} * returns {@code null} */ protected ContextLoader resolveContextLoader(Class<?> testClass, List<ContextConfigurationAttributes> configAttributesList) { Assert.notNull(testClass, "Class must not be null"); Assert.notNull(configAttributesList, "ContextConfigurationAttributes list must not be null"); Class<? extends ContextLoader> contextLoaderClass = resolveExplicitContextLoaderClass(configAttributesList); if (contextLoaderClass == null) { contextLoaderClass = getDefaultContextLoaderClass(testClass); } if (logger.isTraceEnabled()) { logger.trace(String.format("Using ContextLoader class [%s] for test class [%s]", contextLoaderClass.getName(), testClass.getName())); } return BeanUtils.instantiateClass(contextLoaderClass, ContextLoader.class); }
From source file:org.springframework.test.context.support.ActiveProfilesUtils.java
/** * Resolve <em>active bean definition profiles</em> for the supplied {@link Class}. * <p>Note that the {@link ActiveProfiles#inheritProfiles inheritProfiles} flag of * {@link ActiveProfiles @ActiveProfiles} will be taken into consideration. * Specifically, if the {@code inheritProfiles} flag is set to {@code true}, profiles * defined in the test class will be merged with those defined in superclasses. * @param testClass the class for which to resolve the active profiles (must not be * {@code null})//from w w w.j av a2 s . c om * @return the set of active profiles for the specified class, including active * profiles from superclasses if appropriate (never {@code null}) * @see ActiveProfiles * @see ActiveProfilesResolver * @see org.springframework.context.annotation.Profile */ static String[] resolveActiveProfiles(Class<?> testClass) { Assert.notNull(testClass, "Class must not be null"); final List<String[]> profileArrays = new ArrayList<>(); Class<ActiveProfiles> annotationType = ActiveProfiles.class; AnnotationDescriptor<ActiveProfiles> descriptor = MetaAnnotationUtils.findAnnotationDescriptor(testClass, annotationType); if (descriptor == null && logger.isDebugEnabled()) { logger.debug(String.format( "Could not find an 'annotation declaring class' for annotation type [%s] and class [%s]", annotationType.getName(), testClass.getName())); } while (descriptor != null) { Class<?> rootDeclaringClass = descriptor.getRootDeclaringClass(); Class<?> declaringClass = descriptor.getDeclaringClass(); ActiveProfiles annotation = descriptor.synthesizeAnnotation(); if (logger.isTraceEnabled()) { logger.trace(String.format("Retrieved @ActiveProfiles [%s] for declaring class [%s]", annotation, declaringClass.getName())); } Class<? extends ActiveProfilesResolver> resolverClass = annotation.resolver(); if (ActiveProfilesResolver.class == resolverClass) { resolverClass = DefaultActiveProfilesResolver.class; } ActiveProfilesResolver resolver; try { resolver = BeanUtils.instantiateClass(resolverClass, ActiveProfilesResolver.class); } catch (Exception ex) { String msg = String.format( "Could not instantiate ActiveProfilesResolver of type [%s] " + "for test class [%s]", resolverClass.getName(), rootDeclaringClass.getName()); logger.error(msg); throw new IllegalStateException(msg, ex); } String[] profiles = resolver.resolve(rootDeclaringClass); if (!ObjectUtils.isEmpty(profiles)) { profileArrays.add(profiles); } descriptor = (annotation.inheritProfiles() ? MetaAnnotationUtils.findAnnotationDescriptor(rootDeclaringClass.getSuperclass(), annotationType) : null); } // Reverse the list so that we can traverse "down" the hierarchy. Collections.reverse(profileArrays); final Set<String> activeProfiles = new LinkedHashSet<>(); for (String[] profiles : profileArrays) { for (String profile : profiles) { if (StringUtils.hasText(profile)) { activeProfiles.add(profile.trim()); } } } return StringUtils.toStringArray(activeProfiles); }
From source file:org.springmodules.validation.valang.parser.ValangParser.java
public void setFunctionsByName(Map functionsByName) { if (functionsByName == null) { return;//w w w .j av a 2 s . co m } final Map constructorMap = new HashMap(); for (Iterator iter = functionsByName.keySet().iterator(); iter.hasNext();) { Object stringNameObject = iter.next(); if (!(stringNameObject instanceof String)) { throw new IllegalArgumentException("Key for custom functions map must be a string value!"); } String functionName = (String) stringNameObject; Object functionClassNameObject = functionsByName.get(functionName); if (!(functionClassNameObject instanceof String)) { throw new IllegalArgumentException("Value for custom function map must be a string!"); } String functionClassName = (String) functionClassNameObject; Class functionClass = loadClass(functionClassName); if (!(Function.class.isAssignableFrom(functionClass))) { throw new IllegalArgumentException( "Custom function classes must implement org.springmodules.validation.valang.functions.Function!"); } Constructor constructor = null; try { constructor = functionClass.getConstructor(new Class[] { Function[].class, int.class, int.class }); } catch (NoSuchMethodException e) { throw new IllegalArgumentException("Class [" + functionClass.getName() + "] has no constructor with one org.springmodules.validation.valang.functions.Function parameter!"); } constructorMap.put(functionName, constructor); } getVisitor().setVisitor(new ValangVisitor() { public Function getFunction(String name, Function[] functions, int line, int column) { if (constructorMap.containsKey(name)) { Constructor functionConstructor = (Constructor) constructorMap.get(name); return (Function) BeanUtils.instantiateClass(functionConstructor, new Object[] { functions, new Integer(line), new Integer(column) }); } return null; } }); }