Example usage for org.springframework.beans BeanUtils instantiateClass

List of usage examples for org.springframework.beans BeanUtils instantiateClass

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils instantiateClass.

Prototype

public static <T> T instantiateClass(Class<T> clazz) throws BeanInstantiationException 

Source Link

Document

Instantiate a class using its 'primary' constructor (for Kotlin classes, potentially having default arguments declared) or its default constructor (for regular Java classes, expecting a standard no-arg setup).

Usage

From source file:org.springframework.orm.hibernate3.LocalSessionFactoryBean.java

/**
 * Subclasses can override this method to perform custom initialization
 * of the Configuration instance used for SessionFactory creation.
 * The properties of this LocalSessionFactoryBean will be applied to
 * the Configuration object that gets returned here.
 * <p>The default implementation creates a new Configuration instance.
 * A custom implementation could prepare the instance in a specific way,
 * or use a custom Configuration subclass.
 * @return the Configuration instance/* w  ww .  j  av  a2s  .  c o  m*/
 * @throws HibernateException in case of Hibernate initialization errors
 * @see org.hibernate.cfg.Configuration#Configuration()
 */
protected Configuration newConfiguration() throws HibernateException {
    return (Configuration) BeanUtils.instantiateClass(this.configurationClass);
}

From source file:org.springframework.orm.hibernate3.SessionFactoryBuilderSupport.java

/**
 * Instantiate and return an instance of the {@link Configuration} class
 * type for this builder. Subclasses may override in order to customize
 * instantiation logic, but clients should use {@link #doWithConfiguration}
 * to directly customize the {@code Configuration} instance.
 * @see #getDefaultConfigurationClass()//w  w w .j av  a  2s. c  o  m
 * @see #setConfigurationClass(Class)
 * @see #getConfiguration()
 * @see #doWithConfiguration(HibernateConfigurationCallback)
 */
protected Configuration newConfiguration() {
    return BeanUtils.instantiateClass(this.configurationClass);
}

From source file:org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.java

/**
 * 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).// ww w . j a v a  2 s.  c  om
 * @see JpaVendorAdapter#getPersistenceProvider()
 * @see javax.persistence.spi.PersistenceProvider
 * @see javax.persistence.Persistence
 */
public void setPersistenceProviderClass(Class<? extends PersistenceProvider> persistenceProviderClass) {
    this.persistenceProvider = BeanUtils.instantiateClass(persistenceProviderClass);
}

From source file:org.springframework.osgi.extender.internal.support.ExtenderConfiguration.java

protected void addDefaultDependencyFactories() {
    boolean debug = log.isDebugEnabled();

    // default JDK 1.4 processor
    dependencyFactories.add(0, new MandatoryImporterDependencyFactory());

    // load through reflection the dependency and injection processors if running on JDK 1.5 and annotation
    // processing is enabled
    if (processAnnotation) {
        // dependency processor
        Class<?> annotationProcessor = null;
        try {/*from w  w  w.j  av a 2s .  co  m*/
            annotationProcessor = Class.forName(ANNOTATION_DEPENDENCY_FACTORY, false,
                    ExtenderConfiguration.class.getClassLoader());
        } catch (ClassNotFoundException cnfe) {
            log.warn("Spring DM annotation package not found, annotation processing disabled.", cnfe);
            return;
        }
        Object processor = BeanUtils.instantiateClass(annotationProcessor);
        Assert.isInstanceOf(OsgiServiceDependencyFactory.class, processor);
        dependencyFactories.add(1, (OsgiServiceDependencyFactory) processor);

        if (debug)
            log.debug("Succesfully loaded annotation dependency processor [" + ANNOTATION_DEPENDENCY_FACTORY
                    + "]");

        // add injection processor (first in line)
        postProcessors.add(0, new OsgiAnnotationPostProcessor());
        log.info("Spring-DM annotation processing enabled");
    } else {
        if (debug) {
            log.debug("Spring-DM annotation processing disabled; [" + ANNOTATION_DEPENDENCY_FACTORY
                    + "] not loaded");
        }
    }

}

From source file:org.springframework.remoting.jaxrpc.LocalJaxRpcServiceFactory.java

/**
 * Create a JAX-RPC ServiceFactory, either of the specified class
 * or the default./*from   www  . java  2 s . com*/
 * @throws ServiceException if thrown by JAX-RPC methods
 * @see #setServiceFactoryClass
 * @see javax.xml.rpc.ServiceFactory#newInstance()
 */
protected ServiceFactory createServiceFactory() throws ServiceException {
    if (getServiceFactoryClass() != null) {
        return (ServiceFactory) BeanUtils.instantiateClass(getServiceFactoryClass());
    } else {
        return ServiceFactory.newInstance();
    }
}

From source file:org.springframework.scheduling.quartz.SchedulerFactoryBean.java

public void afterPropertiesSet() throws Exception {
    if (this.dataSource == null && this.nonTransactionalDataSource != null) {
        this.dataSource = this.nonTransactionalDataSource;
    }/*ww  w.  ja va2  s .c o m*/

    // Create SchedulerFactory instance.
    SchedulerFactory schedulerFactory = (SchedulerFactory) BeanUtils
            .instantiateClass(this.schedulerFactoryClass);

    initSchedulerFactory(schedulerFactory);

    if (this.dataSource != null) {
        // Make given DataSource available for SchedulerFactory configuration.
        configTimeDataSourceHolder.set(this.dataSource);
    }
    if (this.nonTransactionalDataSource != null) {
        // Make given non-transactional DataSource available for SchedulerFactory configuration.
        configTimeNonTransactionalDataSourceHolder.set(this.nonTransactionalDataSource);
    }

    // Get Scheduler instance from SchedulerFactory.
    try {
        this.scheduler = createScheduler(schedulerFactory, this.schedulerName);
    } finally {
        if (this.dataSource != null) {
            configTimeDataSourceHolder.set(null);
        }
        if (this.nonTransactionalDataSource != null) {
            configTimeNonTransactionalDataSourceHolder.set(null);
        }
    }

    populateSchedulerContext();

    registerListeners();

    registerJobsAndTriggers();

    // Start Scheduler immediately, if demanded.
    if (this.autoStartup) {
        startScheduler(this.scheduler, this.startupDelay);
    }
}

From source file:org.springframework.test.context.support.AbstractContextLoader.java

@SuppressWarnings("unchecked")
private void invokeApplicationContextInitializers(ConfigurableApplicationContext context,
        MergedContextConfiguration mergedConfig) {

    Set<Class<? extends ApplicationContextInitializer<?>>> initializerClasses = mergedConfig
            .getContextInitializerClasses();
    if (initializerClasses.isEmpty()) {
        // no ApplicationContextInitializers have been declared -> nothing to do
        return;/*from  w w  w . jav  a  2  s  .c  o  m*/
    }

    List<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerInstances = new ArrayList<>();
    Class<?> contextClass = context.getClass();

    for (Class<? extends ApplicationContextInitializer<?>> initializerClass : initializerClasses) {
        Class<?> initializerContextClass = GenericTypeResolver.resolveTypeArgument(initializerClass,
                ApplicationContextInitializer.class);
        if (initializerContextClass != null && !initializerContextClass.isInstance(context)) {
            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 "
                            + "context loader: [%s]",
                    initializerClass.getName(), initializerContextClass.getName(), contextClass.getName()));
        }
        initializerInstances.add((ApplicationContextInitializer<ConfigurableApplicationContext>) BeanUtils
                .instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(initializerInstances);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : initializerInstances) {
        initializer.initialize(context);
    }
}

From source file:org.springframework.test.context.support.AbstractTestContextBootstrapper.java

private List<TestExecutionListener> instantiateListeners(
        Collection<Class<? extends TestExecutionListener>> classes) {
    List<TestExecutionListener> listeners = new ArrayList<>(classes.size());
    for (Class<? extends TestExecutionListener> listenerClass : classes) {
        try {//from  w  w  w. j  ava2 s .  co  m
            listeners.add(BeanUtils.instantiateClass(listenerClass));
        } catch (BeanInstantiationException ex) {
            if (ex.getCause() instanceof NoClassDefFoundError) {
                // TestExecutionListener not applicable due to a missing dependency
                if (logger.isDebugEnabled()) {
                    logger.debug(String.format(
                            "Skipping candidate TestExecutionListener [%s] due to a missing dependency. "
                                    + "Specify custom listener classes or make the default listener classes "
                                    + "and their required dependencies available. Offending class: [%s]",
                            listenerClass.getName(), ex.getCause().getMessage()));
                }
            } else {
                throw ex;
            }
        }
    }
    return listeners;
}

From source file:org.springframework.web.context.ContextLoader.java

/**
 * Customize the {@link ConfigurableWebApplicationContext} created by this
 * ContextLoader after config locations have been supplied to the context
 * but before the context is <em>refreshed</em>.
 * <p>The default implementation {@linkplain #determineContextInitializerClasses(ServletContext)
 * determines} what (if any) context initializer classes have been specified through
 * {@linkplain #CONTEXT_INITIALIZER_CLASSES_PARAM context init parameters} and
 * {@linkplain ApplicationContextInitializer#initialize invokes each} with the
 * given web application context.//from  w  w  w .jav a 2s  .  c  o m
 * <p>Any {@code ApplicationContextInitializers} implementing
 * {@link org.springframework.core.Ordered Ordered} or marked with @{@link
 * org.springframework.core.annotation.Order Order} will be sorted appropriately.
 * @param sc the current servlet context
 * @param wac the newly created application context
 * @see #CONTEXT_INITIALIZER_CLASSES_PARAM
 * @see ApplicationContextInitializer#initialize(ConfigurableApplicationContext)
 */
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
    List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = determineContextInitializerClasses(
            sc);

    for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
        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 "
                            + "context loader: [%s]",
                    initializerClass.getName(), initializerContextClass.getName(), wac.getClass().getName()));
        }
        this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
    }

    AnnotationAwareOrderComparator.sort(this.contextInitializers);
    for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
        initializer.initialize(wac);
    }
}

From source file:org.springframework.web.method.annotation.ModelAttributeMethodProcessor.java

/**
 * Construct a new attribute instance with the given constructor.
 * <p>Called from//from www  .  j  av a 2s.  c  o m
 * {@link #createAttribute(String, MethodParameter, WebDataBinderFactory, NativeWebRequest)}
 * after constructor resolution.
 * @param ctor the constructor to use
 * @param attributeName the name of the attribute (never {@code null})
 * @param binderFactory for creating WebDataBinder instance
 * @param webRequest the current request
 * @return the created model attribute (never {@code null})
 * @throws BindException in case of constructor argument binding failure
 * @throws Exception in case of constructor invocation failure
 * @since 5.0
 */
protected Object constructAttribute(Constructor<?> ctor, String attributeName,
        WebDataBinderFactory binderFactory, NativeWebRequest webRequest) throws Exception {

    if (ctor.getParameterCount() == 0) {
        // A single default constructor -> clearly a standard JavaBeans arrangement.
        return BeanUtils.instantiateClass(ctor);
    }

    // A single data class constructor -> resolve constructor arguments from request parameters.
    ConstructorProperties cp = ctor.getAnnotation(ConstructorProperties.class);
    String[] paramNames = (cp != null ? cp.value() : parameterNameDiscoverer.getParameterNames(ctor));
    Assert.state(paramNames != null, () -> "Cannot resolve parameter names for constructor " + ctor);
    Class<?>[] paramTypes = ctor.getParameterTypes();
    Assert.state(paramNames.length == paramTypes.length,
            () -> "Invalid number of parameter names: " + paramNames.length + " for constructor " + ctor);

    Object[] args = new Object[paramTypes.length];
    WebDataBinder binder = binderFactory.createBinder(webRequest, null, attributeName);
    String fieldDefaultPrefix = binder.getFieldDefaultPrefix();
    String fieldMarkerPrefix = binder.getFieldMarkerPrefix();
    boolean bindingFailure = false;

    for (int i = 0; i < paramNames.length; i++) {
        String paramName = paramNames[i];
        Class<?> paramType = paramTypes[i];
        Object value = webRequest.getParameterValues(paramName);
        if (value == null) {
            if (fieldDefaultPrefix != null) {
                value = webRequest.getParameter(fieldDefaultPrefix + paramName);
            }
            if (value == null && fieldMarkerPrefix != null) {
                if (webRequest.getParameter(fieldMarkerPrefix + paramName) != null) {
                    value = binder.getEmptyValue(paramType);
                }
            }
        }
        try {
            MethodParameter methodParam = new MethodParameter(ctor, i);
            if (value == null && methodParam.isOptional()) {
                args[i] = (methodParam.getParameterType() == Optional.class ? Optional.empty() : null);
            } else {
                args[i] = binder.convertIfNecessary(value, paramType, methodParam);
            }
        } catch (TypeMismatchException ex) {
            ex.initPropertyName(paramName);
            binder.getBindingErrorProcessor().processPropertyAccessException(ex, binder.getBindingResult());
            bindingFailure = true;
            args[i] = value;
        }
    }

    if (bindingFailure) {
        if (binder.getBindingResult() instanceof AbstractBindingResult) {
            AbstractBindingResult result = (AbstractBindingResult) binder.getBindingResult();
            for (int i = 0; i < paramNames.length; i++) {
                result.recordFieldValue(paramNames[i], paramTypes[i], args[i]);
            }
        }
        throw new BindException(binder.getBindingResult());
    }

    return BeanUtils.instantiateClass(ctor, args);
}