Java Code Examples for org.springframework.beans.BeanUtils#instantiateClass()

The following examples show how to use org.springframework.beans.BeanUtils#instantiateClass() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SimpleEmailServiceJavaMailSender.java    From spring-cloud-aws with Apache License 2.0 6 votes vote down vote up
@Override
public MimeMessage createMimeMessage() {

	// We have to use reflection as SmartMimeMessage is not package-private
	if (ClassUtils.isPresent(SMART_MIME_MESSAGE_CLASS_NAME,
			ClassUtils.getDefaultClassLoader())) {
		Class<?> smartMimeMessage = ClassUtils.resolveClassName(
				SMART_MIME_MESSAGE_CLASS_NAME, ClassUtils.getDefaultClassLoader());
		Constructor<?> constructor = ClassUtils.getConstructorIfAvailable(
				smartMimeMessage, Session.class, String.class, FileTypeMap.class);
		if (constructor != null) {
			Object mimeMessage = BeanUtils.instantiateClass(constructor, getSession(),
					this.defaultEncoding, this.defaultFileTypeMap);
			return (MimeMessage) mimeMessage;
		}
	}

	return new MimeMessage(getSession());
}
 
Example 2
Source File: WebDelegatingSmartContextLoader.java    From java-technology-stack with MIT License 6 votes vote down vote up
public WebDelegatingSmartContextLoader() {
	if (groovyPresent) {
		try {
			Class<?> loaderClass = ClassUtils.forName(GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME,
				WebDelegatingSmartContextLoader.class.getClassLoader());
			this.xmlLoader = (SmartContextLoader) BeanUtils.instantiateClass(loaderClass);
		}
		catch (Throwable ex) {
			throw new IllegalStateException("Failed to enable support for Groovy scripts; "
					+ "could not load class: " + GROOVY_XML_WEB_CONTEXT_LOADER_CLASS_NAME, ex);
		}
	}
	else {
		this.xmlLoader = new GenericXmlWebContextLoader();
	}

	this.annotationConfigLoader = new AnnotationConfigWebContextLoader();
}
 
Example 3
Source File: FrameworkServlet.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
			throw new ApplicationContextException(String.format(
					"Could not apply context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet: [%s]", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (ClassNotFoundException ex) {
		throw new ApplicationContextException(String.format("Could not load class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example 4
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
	Class<?> contextClass = getContextClass();
	if (this.logger.isDebugEnabled()) {
		this.logger.debug("Servlet with name '" + getServletName() +
				"' will try to create custom WebApplicationContext context of class '" +
				contextClass.getName() + "'" + ", using parent context [" + parent + "]");
	}
	if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
		throw new ApplicationContextException(
				"Fatal initialization error in servlet with name '" + getServletName() +
				"': custom WebApplicationContext class [" + contextClass.getName() +
				"] is not of type ConfigurableWebApplicationContext");
	}
	ConfigurableWebApplicationContext wac =
			(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

	wac.setEnvironment(getEnvironment());
	wac.setParent(parent);
	wac.setConfigLocation(getContextConfigLocation());

	configureAndRefreshWebApplicationContext(wac);

	return wac;
}
 
Example 5
Source File: FrameworkServlet.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
private ApplicationContextInitializer<ConfigurableApplicationContext> loadInitializer(
		String className, ConfigurableApplicationContext wac) {
	try {
		Class<?> initializerClass = ClassUtils.forName(className, wac.getClassLoader());
		Class<?> initializerContextClass =
				GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
		if (initializerContextClass != null) {
			Assert.isAssignable(initializerContextClass, wac.getClass(), String.format(
					"Could not add context initializer [%s] since its generic parameter [%s] " +
					"is not assignable from the type of application context used by this " +
					"framework servlet [%s]: ", initializerClass.getName(), initializerContextClass.getName(),
					wac.getClass().getName()));
		}
		return BeanUtils.instantiateClass(initializerClass, ApplicationContextInitializer.class);
	}
	catch (Exception ex) {
		throw new IllegalArgumentException(String.format("Could not instantiate class [%s] specified " +
				"via 'contextInitializerClasses' init-param", className), ex);
	}
}
 
Example 6
Source File: StandardJmsActivationSpecFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public ActivationSpec createActivationSpec(ResourceAdapter adapter, JmsActivationSpecConfig config) {
	Class<?> activationSpecClassToUse = this.activationSpecClass;
	if (activationSpecClassToUse == null) {
		activationSpecClassToUse = determineActivationSpecClass(adapter);
		if (activationSpecClassToUse == null) {
			throw new IllegalStateException("Property 'activationSpecClass' is required");
		}
	}

	ActivationSpec spec = (ActivationSpec) BeanUtils.instantiateClass(activationSpecClassToUse);
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(spec);
	if (this.defaultProperties != null) {
		bw.setPropertyValues(this.defaultProperties);
	}
	populateActivationSpecProperties(bw, config);
	return spec;
}
 
Example 7
Source File: DefaultNamespaceHandlerResolver.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Locate the {@link NamespaceHandler} for the supplied namespace URI
 * from the configured mappings.
 * @param namespaceUri the relevant namespace URI
 * @return the located {@link NamespaceHandler}, or {@code null} if none found
 */
@Override
@Nullable
public NamespaceHandler resolve(String namespaceUri) {
	Map<String, Object> handlerMappings = getHandlerMappings();
	Object handlerOrClassName = handlerMappings.get(namespaceUri);
	if (handlerOrClassName == null) {
		return null;
	}
	else if (handlerOrClassName instanceof NamespaceHandler) {
		return (NamespaceHandler) handlerOrClassName;
	}
	else {
		String className = (String) handlerOrClassName;
		try {
			Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
			if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
				throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
						"] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
			}
			NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
			namespaceHandler.init();
			handlerMappings.put(namespaceUri, namespaceHandler);
			return namespaceHandler;
		}
		catch (ClassNotFoundException ex) {
			throw new FatalBeanException("Could not find NamespaceHandler class [" + className +
					"] for namespace [" + namespaceUri + "]", ex);
		}
		catch (LinkageError err) {
			throw new FatalBeanException("Unresolvable class definition for NamespaceHandler class [" +
					className + "] for namespace [" + namespaceUri + "]", err);
		}
	}
}
 
Example 8
Source File: JasperReportsMultiFormatView.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Locates the format key in the model using the configured discriminator key and uses this
 * key to lookup the appropriate view class from the mappings. The rendering of the
 * report is then delegated to an instance of that view class.
 */
@Override
protected void renderReport(JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response)
		throws Exception {

	String format = (String) model.get(this.formatKey);
	if (format == null) {
		throw new IllegalArgumentException("No format found in model");
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Rendering report using format mapping key [" + format + "]");
	}

	Class<? extends AbstractJasperReportsView> viewClass = this.formatMappings.get(format);
	if (viewClass == null) {
		throw new IllegalArgumentException("Format discriminator [" + format + "] is not a configured mapping");
	}

	if (logger.isDebugEnabled()) {
		logger.debug("Rendering report using view class [" + viewClass.getName() + "]");
	}

	AbstractJasperReportsView view = BeanUtils.instantiateClass(viewClass);
	// Can skip most initialization since all relevant URL processing
	// has been done - just need to convert parameters on the sub view.
	view.setExporterParameters(getExporterParameters());
	view.setConvertedExporterParameters(getConvertedExporterParameters());

	// Prepare response and render report.
	populateContentDispositionIfNecessary(response, format);
	view.renderReport(populatedReport, model, response);
}
 
Example 9
Source File: TilesConfigurer.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected PreparerFactory createPreparerFactory(ApplicationContext context) {
	if (preparerFactoryClass != null) {
		return BeanUtils.instantiateClass(preparerFactoryClass);
	}
	else {
		return super.createPreparerFactory(context);
	}
}
 
Example 10
Source File: SimpleInstantiationStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
	// Don't override the class with CGLIB if no overrides.
	if (!bd.hasMethodOverrides()) {
		Constructor<?> constructorToUse;
		synchronized (bd.constructorArgumentLock) {
			constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
			if (constructorToUse == null) {
				final Class<?> clazz = bd.getBeanClass();
				if (clazz.isInterface()) {
					throw new BeanInstantiationException(clazz, "Specified class is an interface");
				}
				try {
					if (System.getSecurityManager() != null) {
						constructorToUse = AccessController.doPrivileged(
								(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
					}
					else {
						constructorToUse = clazz.getDeclaredConstructor();
					}
					bd.resolvedConstructorOrFactoryMethod = constructorToUse;
				}
				catch (Throwable ex) {
					throw new BeanInstantiationException(clazz, "No default constructor found", ex);
				}
			}
		}
		return BeanUtils.instantiateClass(constructorToUse);
	}
	else {
		// Must generate CGLIB subclass.
		return instantiateWithMethodInjection(bd, beanName, owner);
	}
}
 
Example 11
Source File: JtaTransactionManagerFactoryBean.java    From java-technology-stack with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public JtaTransactionManagerFactoryBean() {
	String className = resolveJtaTransactionManagerClassName();
	try {
		Class<? extends JtaTransactionManager> clazz = (Class<? extends JtaTransactionManager>)
				ClassUtils.forName(className, JtaTransactionManagerFactoryBean.class.getClassLoader());
		this.transactionManager = BeanUtils.instantiateClass(clazz);
	}
	catch (ClassNotFoundException ex) {
		throw new IllegalStateException("Failed to load JtaTransactionManager class: " + className, ex);
	}
}
 
Example 12
Source File: StubWebApplicationContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
	return BeanUtils.instantiateClass(beanClass);
}
 
Example 13
Source File: StubWebApplicationContext.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@Override
public Object createBean(Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
	return BeanUtils.instantiateClass(beanClass);
}
 
Example 14
Source File: ConditionEvaluator.java    From java-technology-stack with MIT License 4 votes vote down vote up
private Condition getCondition(String conditionClassName, @Nullable ClassLoader classloader) {
	Class<?> conditionClass = ClassUtils.resolveClassName(conditionClassName, classloader);
	return (Condition) BeanUtils.instantiateClass(conditionClass);
}
 
Example 15
Source File: ComponentScanAnnotationParser.java    From java-technology-stack with MIT License 4 votes vote down vote up
private List<TypeFilter> typeFiltersFor(AnnotationAttributes filterAttributes) {
	List<TypeFilter> typeFilters = new ArrayList<>();
	FilterType filterType = filterAttributes.getEnum("type");

	for (Class<?> filterClass : filterAttributes.getClassArray("classes")) {
		switch (filterType) {
			case ANNOTATION:
				Assert.isAssignable(Annotation.class, filterClass,
						"@ComponentScan ANNOTATION type filter requires an annotation type");
				@SuppressWarnings("unchecked")
				Class<Annotation> annotationType = (Class<Annotation>) filterClass;
				typeFilters.add(new AnnotationTypeFilter(annotationType));
				break;
			case ASSIGNABLE_TYPE:
				typeFilters.add(new AssignableTypeFilter(filterClass));
				break;
			case CUSTOM:
				Assert.isAssignable(TypeFilter.class, filterClass,
						"@ComponentScan CUSTOM type filter requires a TypeFilter implementation");
				TypeFilter filter = BeanUtils.instantiateClass(filterClass, TypeFilter.class);
				ParserStrategyUtils.invokeAwareMethods(
						filter, this.environment, this.resourceLoader, this.registry);
				typeFilters.add(filter);
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with Class value: " + filterType);
		}
	}

	for (String expression : filterAttributes.getStringArray("pattern")) {
		switch (filterType) {
			case ASPECTJ:
				typeFilters.add(new AspectJTypeFilter(expression, this.resourceLoader.getClassLoader()));
				break;
			case REGEX:
				typeFilters.add(new RegexPatternTypeFilter(Pattern.compile(expression)));
				break;
			default:
				throw new IllegalArgumentException("Filter type not supported with String pattern: " + filterType);
		}
	}

	return typeFilters;
}
 
Example 16
Source File: SimpleDriverDataSource.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Specify the JDBC Driver implementation class to use.
 * <p>An instance of this Driver class will be created and held
 * within the SimpleDriverDataSource.
 * @see #setDriver
 */
public void setDriverClass(Class<? extends Driver> driverClass) {
	this.driver = BeanUtils.instantiateClass(driverClass);
}
 
Example 17
Source File: ResourceAdapterFactoryBean.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Specify the target JCA ResourceAdapter as class, to be instantiated
 * with its default configuration.
 * <p>Alternatively, specify a pre-configured ResourceAdapter instance
 * through the "resourceAdapter" property.
 * @see #setResourceAdapter
 */
public void setResourceAdapterClass(Class<? extends ResourceAdapter> resourceAdapterClass) {
	this.resourceAdapter = BeanUtils.instantiateClass(resourceAdapterClass);
}
 
Example 18
Source File: SimpleDriverDataSource.java    From effectivejava with Apache License 2.0 2 votes vote down vote up
/**
 * Specify the JDBC Driver implementation class to use.
 * <p>An instance of this Driver class will be created and held
 * within the SimpleDriverDataSource.
 * @see #setDriver
 */
public void setDriverClass(Class<? extends Driver> driverClass) {
	this.driver = BeanUtils.instantiateClass(driverClass);
}
 
Example 19
Source File: AbstractEntityManagerFactoryBean.java    From java-technology-stack with MIT License 2 votes vote down vote up
/**
 * Set the PersistenceProvider implementation class to use for creating the
 * EntityManagerFactory. If not specified, the persistence provider will be
 * taken from the JpaVendorAdapter (if any) or retrieved through scanning
 * (as far as possible).
 * @see JpaVendorAdapter#getPersistenceProvider()
 * @see javax.persistence.spi.PersistenceProvider
 * @see javax.persistence.Persistence
 */
public void setPersistenceProviderClass(Class<? extends PersistenceProvider> persistenceProviderClass) {
	this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass);
}
 
Example 20
Source File: SimpleDriverDataSource.java    From spring-analysis-note with MIT License 2 votes vote down vote up
/**
 * Specify the JDBC Driver implementation class to use.
 * <p>An instance of this Driver class will be created and held
 * within the SimpleDriverDataSource.
 * @see #setDriver
 */
public void setDriverClass(Class<? extends Driver> driverClass) {
	this.driver = BeanUtils.instantiateClass(driverClass);
}