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

The following examples show how to use org.springframework.beans.BeanUtils#instantiate() . 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: CglibSubclassingInstantiationStrategy.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
public Object instantiate(Constructor<?> ctor, Object... args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception ex) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
					"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
		}
	}
	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] {NoOp.INSTANCE,
			new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
			new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
	return instance;
}
 
Example 2
Source File: TilesConfigurer.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(ApplicationContext applicationContext,
		LocaleResolver resolver) {

	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof ApplicationContextAware) {
			((ApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO", createLocaleDefinitionDao(applicationContext, resolver));
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, resolver);
	}
}
 
Example 3
Source File: FastJsonAutoConfiguration.java    From utils with Apache License 2.0 6 votes vote down vote up
@Bean
@ConditionalOnMissingBean(com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter.class)
public HttpMessageConverters customConverters(FastJsonHttpMessageConverter converter) {
    Collection<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();

    if (null == converter) {
        Class<?> converterClass = properties.getConverter();
        converter = (FastJsonHttpMessageConverter) BeanUtils.instantiate(converterClass);
    }

    FastJsonConfig config = new FastJsonConfig();
    List<SerializerFeature> features = properties.getFeatures();
    if (!CollectionUtils.isBlank(features)) {
        SerializerFeature[] featureArray = new SerializerFeature[features.size()];
        config.setSerializerFeatures(features.toArray(featureArray));
    }

    converter.setFastJsonConfig(config);
    messageConverters.add(converter);

    return new HttpMessageConverters(true, messageConverters);
}
 
Example 4
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private <T extends ServiceCallResult> T getAction(UriComponentsBuilder ub, Class<T> responseType, Supplier<T> factory) {
    if(factory == null) {
        factory = () -> BeanUtils.instantiate(responseType);
    }
    URI uri = ub.build().toUri();
    T resp;
    try {
        ResponseEntity<T> entity = getFast(() -> {
            return restTemplate.getForEntity(uri, responseType);
        });
        resp = entity.getBody();
        if(resp == null) {
            resp = factory.get();
        }
        resp.setCode(ResultCode.OK);
        return resp;
    } catch (HttpStatusCodeException e) {
        log.warn("Failed to execute GET on {}, due to {}", uri, e.toString());
        resp = factory.get();
        processStatusCodeException(e, resp, uri);
        return resp;
    }
}
 
Example 5
Source File: TilesConfigurer.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
protected DefinitionsFactory createDefinitionsFactory(TilesApplicationContext applicationContext,
		TilesRequestContextFactory contextFactory, LocaleResolver resolver) {
	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiate(definitionsFactoryClass);
		if (factory instanceof TilesApplicationContextAware) {
			((TilesApplicationContextAware) factory).setApplicationContext(applicationContext);
		}
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(factory);
		if (bw.isWritableProperty("localeResolver")) {
			bw.setPropertyValue("localeResolver", resolver);
		}
		if (bw.isWritableProperty("definitionDAO")) {
			bw.setPropertyValue("definitionDAO",
					createLocaleDefinitionDao(applicationContext, contextFactory, resolver));
		}
		if (factory instanceof Refreshable) {
			((Refreshable) factory).refresh();
		}
		return factory;
	}
	else {
		return super.createDefinitionsFactory(applicationContext, contextFactory, resolver);
	}
}
 
Example 6
Source File: TilesConfigurer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected PreparerFactory createPreparerFactory(ApplicationContext context) {
	if (preparerFactoryClass != null) {
		return BeanUtils.instantiate(preparerFactoryClass);
	}
	else {
		return super.createPreparerFactory(context);
	}
}
 
Example 7
Source File: DockerServiceImpl.java    From haven-platform with Apache License 2.0 5 votes vote down vote up
private <T extends ServiceCallResult> T postAction(UriComponentsBuilder ub, Object cmd, Class<T> responseType, Supplier<T> factory) {
    if(factory == null) {
        factory = () -> BeanUtils.instantiate(responseType);
    }
    URI url = ub.build().toUri();
    T resp;
    try {
        ResponseEntity<T> entity = getSlow(() -> {
            HttpEntity<?> req = null;
            if(cmd != null) {
                req = wrapEntity(cmd);
            }
            return restTemplate.postForEntity(url, req, responseType);
        });
        resp = entity.getBody();
        if(resp == null) {
            resp = factory.get();
        }
        resp.setCode(ResultCode.OK);
        resp.setStatus(entity.getStatusCode());
        return resp;
    } catch (HttpStatusCodeException e) {
        resp = factory.get();
        processStatusCodeException(e, resp, url);
        return resp;
    }
}
 
Example 8
Source File: ShiroAutoConfiguration.java    From spring-boot-shiro with Apache License 2.0 5 votes vote down vote up
private Map<String, Filter> instantiateFilterClasses(Map<String, Class<? extends Filter>> filters) {
    Map<String, Filter> filterMap = null;
    if (filters != null) {
        filterMap = new LinkedHashMap<String, Filter>();
        for (String name : filters.keySet()) {
            Class<? extends Filter> clazz = filters.get(name);
            Filter f = BeanUtils.instantiate(clazz);
            filterMap.put(name, f);
        }
    }
    return filterMap;
}
 
Example 9
Source File: CglibSubclassingInstantiationStrategy.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance of a dynamically generated subclass implementing the
 * required lookups.
 * @param ctor constructor to use. If this is {@code null}, use the
 * no-arg constructor (no parameterization, or Setter Injection)
 * @param args arguments to use for the constructor.
 * Ignored if the {@code ctor} parameter is {@code null}.
 * @return new instance of the dynamically generated subclass
 */
Object instantiate(Constructor<?> ctor, Object[] args) {
	Class<?> subclass = createEnhancedSubclass(this.beanDefinition);

	Object instance;
	if (ctor == null) {
		instance = BeanUtils.instantiate(subclass);
	}
	else {
		try {
			Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
			instance = enhancedSubclassConstructor.newInstance(args);
		}
		catch (Exception e) {
			throw new BeanInstantiationException(this.beanDefinition.getBeanClass(), String.format(
				"Failed to invoke construcor for CGLIB enhanced subclass [%s]", subclass.getName()), e);
		}
	}

	// SPR-10785: set callbacks directly on the instance instead of in the
	// enhanced class (via the Enhancer) in order to avoid memory leaks.
	Factory factory = (Factory) instance;
	factory.setCallbacks(new Callback[] { NoOp.INSTANCE,//
		new LookupOverrideMethodInterceptor(beanDefinition, owner),//
		new ReplaceOverrideMethodInterceptor(beanDefinition, owner) });

	return instance;
}
 
Example 10
Source File: TilesConfigurer.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected PreparerFactory createPreparerFactory(ApplicationContext context) {
	if (preparerFactoryClass != null) {
		return BeanUtils.instantiate(preparerFactoryClass);
	}
	else {
		return super.createPreparerFactory(context);
	}
}
 
Example 11
Source File: MethodInvokingJobDetailFactoryBean.java    From uncode-schedule with Apache License 2.0 5 votes vote down vote up
public void afterPropertiesSet() throws ClassNotFoundException, NoSuchMethodException {
  prepare();

  // Use specific name if given, else fall back to bean name.
  String name = (this.name != null ? this.name : this.beanName);

  // Consider the concurrent flag to choose between stateful and stateless job.
  Class jobClass = (this.concurrent ? MethodInvokingJob.class : StatefulMethodInvokingJob.class);

  // Build JobDetail instance.
  if (jobDetailImplClass != null) {
    // Using Quartz 2.0 JobDetailImpl class...
    this.jobDetail = (JobDetail) BeanUtils.instantiate(jobDetailImplClass);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this.jobDetail);
    bw.setPropertyValue("name", name);
    bw.setPropertyValue("group", this.group);
    bw.setPropertyValue("jobClass", jobClass);
    bw.setPropertyValue("durability", true);
    ((JobDataMap) bw.getPropertyValue("jobDataMap")).put("methodInvoker", this);
  } else { //@wjw_add: 添加对Quartz1.X的支持!
    // Using Quartz 1.x JobDetail class...
    this.jobDetail = new JobDetail(name, this.group, jobClass);
    this.jobDetail.setVolatility(true);
    this.jobDetail.setDurability(true);
    this.jobDetail.getJobDataMap().put("methodInvoker", this);
  }

  // Register job listener names.
  if (this.jobListenerNames != null) {
    for (String jobListenerName : this.jobListenerNames) {
      if (jobDetailImplClass != null) {
        throw new IllegalStateException("Non-global JobListeners not supported on Quartz 2 - " +
            "manually register a Matcher against the Quartz ListenerManager instead");
      }
      //this.jobDetail.addJobListener(jobListenerName);
    }
  }

  postProcessJobDetail(this.jobDetail);
}
 
Example 12
Source File: EntityModel.java    From webanno with Apache License 2.0 5 votes vote down vote up
@Override
protected T load()
{
    if (entityClass == null) {
        return null;
    }
    
    if (id == null || id.longValue() == 0) {
        return BeanUtils.instantiate(entityClass);
    }
    else {
        return getEntityManager().find(entityClass, id);
    }
}
 
Example 13
Source File: ShiroAutoConfiguration.java    From shiro-spring-boot with Apache License 2.0 5 votes vote down vote up
@Bean(name = "realm")
@DependsOn("lifecycleBeanPostProcessor")
@ConditionalOnMissingBean
public Realm realm() {
	Class<?> relmClass = properties.getRealm();
	return (Realm) BeanUtils.instantiate(relmClass);
}
 
Example 14
Source File: ConfigurableFieldFactory.java    From jdal with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
public Field createField(Item item, Object propertyId, Component uiContext) {
	Class<Field> clazz = fieldMap.get(propertyId);
	if (clazz != null) {
		try {
			return BeanUtils.instantiate(clazz);
		}
		catch(BeanInstantiationException bie) {
			log.error(bie);
		}
	}
	
	return null;
}
 
Example 15
Source File: ShiroAutoConfiguration.java    From utils with Apache License 2.0 5 votes vote down vote up
private Map<String, Filter> instantiateFilterClasses(Map<String, Class<? extends Filter>> filters) {
    Map<String, Filter> filterMap = null;
    if (filters != null) {
        filterMap = new LinkedHashMap<String, Filter>();
        for (String name : filters.keySet()) {
            Class<? extends Filter> clazz = filters.get(name);
            Filter f = BeanUtils.instantiate(clazz);
            filterMap.put(name, f);
        }
    }

    return filterMap;
}
 
Example 16
Source File: CollectionUtil.java    From stategen with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({ "rawtypes", "unchecked" })
public static <K, L extends List> GetOrCreateWrap<L> getOrCreateList(K key, Map<K, L> sourceMap, Class<? extends List> listClz) {
    List destList = sourceMap.get(key);
    boolean isCreate = false;
    if (destList == null) {
        destList = BeanUtils.instantiate(listClz);
        sourceMap.put(key, (L) destList);
        isCreate = true;
    }
    return new GetOrCreateWrap(destList, isCreate);
}
 
Example 17
Source File: ShiroAutoConfiguration.java    From utils with Apache License 2.0 5 votes vote down vote up
public AuthFilter authFilter() {
    Class<?> authClass = shiroProperties.getAuthClass();
    AuthFilter filter = (AuthFilter) BeanUtils.instantiate(authClass);
    filter.setLoginUrl(shiroProperties.getLoginUrl());
    filter.setSuccessUrl(shiroProperties.getSuccessUrl());
    filter.setUsernameParam(authFilterProperties.getUserParamName());
    filter.setPasswordParam(authFilterProperties.getPasswordParamName());
    filter.setRememberMeParam(authFilterProperties.getRememberMeParamName());
    filter.setDataParamName(authFilterProperties.getDataParamName());

    return filter;
}
 
Example 18
Source File: ShiroAutoConfiguration.java    From shiro-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
@Bean(name = "realm")
@DependsOn("lifecycleBeanPostProcessor")
@ConditionalOnMissingBean
public Realm realm() {
	Class<?> relmClass = properties.getRealm();
	return (Realm) BeanUtils.instantiate(relmClass);
}
 
Example 19
Source File: BeanPropertyRowMapper.java    From effectivejava with Apache License 2.0 4 votes vote down vote up
/**
 * Extract the values for all columns in the current row.
 * <p>Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData
 */
@Override
public T mapRow(ResultSet rs, int rowNumber) throws SQLException {
	Assert.state(this.mappedClass != null, "Mapped class was not specified");
	T mappedObject = BeanUtils.instantiate(this.mappedClass);
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(mappedObject);
	initBeanWrapper(bw);

	ResultSetMetaData rsmd = rs.getMetaData();
	int columnCount = rsmd.getColumnCount();
	Set<String> populatedProperties = (isCheckFullyPopulated() ? new HashSet<String>() : null);

	for (int index = 1; index <= columnCount; index++) {
		String column = JdbcUtils.lookupColumnName(rsmd, index);
		PropertyDescriptor pd = this.mappedFields.get(column.replaceAll(" ", "").toLowerCase());
		if (pd != null) {
			try {
				Object value = getColumnValue(rs, index, pd);
				if (logger.isDebugEnabled() && rowNumber == 0) {
					logger.debug("Mapping column '" + column + "' to property '" +
							pd.getName() + "' of type " + pd.getPropertyType());
				}
				try {
					bw.setPropertyValue(pd.getName(), value);
				}
				catch (TypeMismatchException e) {
					if (value == null && primitivesDefaultedForNullValue) {
						logger.debug("Intercepted TypeMismatchException for row " + rowNumber +
								" and column '" + column + "' with value " + value +
								" when setting property '" + pd.getName() + "' of type " + pd.getPropertyType() +
								" on object: " + mappedObject);
					}
					else {
						throw e;
					}
				}
				if (populatedProperties != null) {
					populatedProperties.add(pd.getName());
				}
			}
			catch (NotWritablePropertyException ex) {
				throw new DataRetrievalFailureException(
						"Unable to map column " + column + " to property " + pd.getName(), ex);
			}
		}
	}

	if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
		throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " +
				"necessary to populate object of class [" + this.mappedClass + "]: " + this.mappedProperties);
	}

	return mappedObject;
}
 
Example 20
Source File: StubWebApplicationContext.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) {
	return BeanUtils.instantiate(beanClass);
}