Java 类org.springframework.beans.BeanWrapper 实例源码

项目:gemini.blueprint    文件:CMUtils.java   
/**
 * Injects the properties from the given Map to the given object. Additionally, a bean factory can be passed in for
 * copying property editors inside the injector.
 * 
 * @param instance bean instance to configure
 * @param properties
 * @param beanFactory
 */
public static void applyMapOntoInstance(Object instance, Map<String, ?> properties, AbstractBeanFactory beanFactory) {
    if (properties != null && !properties.isEmpty()) {
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(instance);
        beanWrapper.setAutoGrowNestedPaths(true);

        // configure bean wrapper (using method from Spring 2.5.6)
        if (beanFactory != null) {
            beanFactory.copyRegisteredEditorsTo(beanWrapper);
        }
        for (Iterator<?> iterator = properties.entrySet().iterator(); iterator.hasNext();) {
            Map.Entry<String, ?> entry = (Map.Entry<String, ?>) iterator.next();
            String propertyName = entry.getKey();
            if (beanWrapper.isWritableProperty(propertyName)) {
                beanWrapper.setPropertyValue(propertyName, entry.getValue());
            }
        }
    }
}
项目:lams    文件:QuartzJobBean.java   
/**
 * This implementation applies the passed-in job data map as bean property
 * values, and delegates to {@code executeInternal} afterwards.
 * @see #executeInternal
 */
@Override
public final void execute(JobExecutionContext context) throws JobExecutionException {
    try {
        // Reflectively adapting to differences between Quartz 1.x and Quartz 2.0...
        Scheduler scheduler = (Scheduler) ReflectionUtils.invokeMethod(getSchedulerMethod, context);
        Map<?, ?> mergedJobDataMap = (Map<?, ?>) ReflectionUtils.invokeMethod(getMergedJobDataMapMethod, context);

        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
        MutablePropertyValues pvs = new MutablePropertyValues();
        pvs.addPropertyValues(scheduler.getContext());
        pvs.addPropertyValues(mergedJobDataMap);
        bw.setPropertyValues(pvs, true);
    }
    catch (SchedulerException ex) {
        throw new JobExecutionException(ex);
    }
    executeInternal(context);
}
项目:lams    文件:SpringBeanJobFactory.java   
/**
 * Create the job instance, populating it with property values taken
 * from the scheduler context, job data map and trigger data map.
 */
@Override
protected Object createJobInstance(TriggerFiredBundle bundle) throws Exception {
    Object job = super.createJobInstance(bundle);
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
    if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) {
        MutablePropertyValues pvs = new MutablePropertyValues();
        if (this.schedulerContext != null) {
            pvs.addPropertyValues(this.schedulerContext);
        }
        pvs.addPropertyValues(getJobDetailDataMap(bundle));
        pvs.addPropertyValues(getTriggerDataMap(bundle));
        if (this.ignoredUnknownProperties != null) {
            for (String propName : this.ignoredUnknownProperties) {
                if (pvs.contains(propName) && !bw.isWritableProperty(propName)) {
                    pvs.removePropertyValue(propName);
                }
            }
            bw.setPropertyValues(pvs);
        }
        else {
            bw.setPropertyValues(pvs, true);
        }
    }
    return job;
}
项目:lams    文件:TaskExecutorFactoryBean.java   
@Override
public void afterPropertiesSet() throws Exception {
    BeanWrapper bw = new BeanWrapperImpl(ThreadPoolTaskExecutor.class);
    determinePoolSizeRange(bw);
    if (this.queueCapacity != null) {
        bw.setPropertyValue("queueCapacity", this.queueCapacity);
    }
    if (this.keepAliveSeconds != null) {
        bw.setPropertyValue("keepAliveSeconds", this.keepAliveSeconds);
    }
    if (this.rejectedExecutionHandler != null) {
        bw.setPropertyValue("rejectedExecutionHandler", this.rejectedExecutionHandler);
    }
    if (this.beanName != null) {
        bw.setPropertyValue("threadNamePrefix", this.beanName + "-");
    }
    this.target = (TaskExecutor) bw.getWrappedInstance();
    if (this.target instanceof InitializingBean) {
        ((InitializingBean) this.target).afterPropertiesSet();
    }
}
项目:lams    文件:AnnotationBeanUtils.java   
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) {
    Set<String> excluded =  new HashSet<String>(Arrays.asList(excludedProperties));
    Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    for (Method annotationProperty : annotationProperties) {
        String propertyName = annotationProperty.getName();
        if ((!excluded.contains(propertyName)) && bw.isWritableProperty(propertyName)) {
            Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
            if (valueResolver != null && value instanceof String) {
                value = valueResolver.resolveStringValue((String) value);
            }
            bw.setPropertyValue(propertyName, value);
        }
    }
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
    markBeanAsCreated(beanName);
    BeanDefinition mbd = getMergedBeanDefinition(beanName);
    RootBeanDefinition bd = null;
    if (mbd instanceof RootBeanDefinition) {
        RootBeanDefinition rbd = (RootBeanDefinition) mbd;
        bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
    }
    if (!mbd.isPrototype()) {
        if (bd == null) {
            bd = new RootBeanDefinition(mbd);
        }
        bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
    }
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    initBeanWrapper(bw);
    populateBean(beanName, bd, bw);
    return initializeBean(beanName, existingBean, bd);
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Obtain a "shortcut" non-singleton FactoryBean instance to use for a
 * {@code getObjectType()} call, without full initialization
 * of the FactoryBean.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return the FactoryBean instance, or {@code null} to indicate
 * that we couldn't obtain a shortcut FactoryBean instance
 */
private FactoryBean<?> getNonSingletonFactoryBeanForTypeCheck(String beanName, RootBeanDefinition mbd) {
    if (isPrototypeCurrentlyInCreation(beanName)) {
        return null;
    }
    Object instance = null;
    try {
        // Mark this bean as currently in creation, even if just partially.
        beforePrototypeCreation(beanName);
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        instance = resolveBeforeInstantiation(beanName, mbd);
        if (instance == null) {
            BeanWrapper bw = createBeanInstance(beanName, mbd, null);
            instance = bw.getWrappedInstance();
        }
    }
    finally {
        // Finished partial creation of this bean.
        afterPrototypeCreation(beanName);
    }
    return getFactoryBean(beanName, instance);
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                }
            }, getAccessControlContext());
        }
        else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Fill in any missing property values with references to
 * other beans in this factory if autowire is set to "byName".
 * @param beanName the name of the bean we're wiring up.
 * Useful for debugging messages; not used functionally.
 * @param mbd bean definition to update through autowiring
 * @param bw BeanWrapper from which we can obtain information about the bean
 * @param pvs the PropertyValues to register wired objects with
 */
protected void autowireByName(
        String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

    String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
    for (String propertyName : propertyNames) {
        if (containsBean(propertyName)) {
            Object bean = getBean(propertyName);
            pvs.add(propertyName, bean);
            registerDependentBean(propertyName, beanName);
            if (logger.isDebugEnabled()) {
                logger.debug("Added autowiring by name from bean name '" + beanName +
                        "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
            }
        }
        else {
            if (logger.isTraceEnabled()) {
                logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                        "' by name: no matching bean found");
            }
        }
    }
}
项目:lams    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Extract a filtered set of PropertyDescriptors from the given BeanWrapper,
 * excluding ignored dependency types or properties defined on ignored dependency interfaces.
 * @param bw the BeanWrapper the bean was created with
 * @param cache whether to cache filtered PropertyDescriptors for the given bean Class
 * @return the filtered PropertyDescriptors
 * @see #isExcludedFromDependencyCheck
 * @see #filterPropertyDescriptorsForDependencyCheck(org.springframework.beans.BeanWrapper)
 */
protected PropertyDescriptor[] filterPropertyDescriptorsForDependencyCheck(BeanWrapper bw, boolean cache) {
    PropertyDescriptor[] filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
    if (filtered == null) {
        if (cache) {
            synchronized (this.filteredPropertyDescriptorsCache) {
                filtered = this.filteredPropertyDescriptorsCache.get(bw.getWrappedClass());
                if (filtered == null) {
                    filtered = filterPropertyDescriptorsForDependencyCheck(bw);
                    this.filteredPropertyDescriptorsCache.put(bw.getWrappedClass(), filtered);
                }
            }
        }
        else {
            filtered = filterPropertyDescriptorsForDependencyCheck(bw);
        }
    }
    return filtered;
}
项目:lams    文件:PropertyPathFactoryBean.java   
@Override
public Object getObject() throws BeansException {
    BeanWrapper target = this.targetBeanWrapper;
    if (target != null) {
        if (logger.isWarnEnabled() && this.targetBeanName != null &&
                this.beanFactory instanceof ConfigurableBeanFactory &&
                ((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
            logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " +
                    "reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
        }
    }
    else {
        // Fetch prototype target bean...
        Object bean = this.beanFactory.getBean(this.targetBeanName);
        target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    }
    return target.getPropertyValue(this.propertyPath);
}
项目:spring-data-gclouddatastore    文件:GcloudDatastoreEntityInformation.java   
@SuppressWarnings("unchecked")
@Override
public ID getId(T entity) {
    Class<?> domainClass = getJavaType();
    while (domainClass != Object.class) {
        for (Field field : domainClass.getDeclaredFields()) {
            if (field.getAnnotation(Id.class) != null) {
                try {
                    return (ID) field.get(entity);
                }
                catch (IllegalArgumentException | IllegalAccessException e) {
                    BeanWrapper beanWrapper = PropertyAccessorFactory
                            .forBeanPropertyAccess(entity);
                    return (ID) beanWrapper.getPropertyValue(field.getName());
                }
            }
        }
        domainClass = domainClass.getSuperclass();
    }
    throw new IllegalStateException("id not found");
}
项目:yadaframework    文件:YadaQuartzJobFactory.java   
protected void initJob(TriggerFiredBundle bundle, Object job) {
    // The following code is copied from SpringBeanJobFactory in spring-context-support-4.2.5.RELEASE
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
    if (isEligibleForPropertyPopulation(bw.getWrappedInstance())) {
        MutablePropertyValues pvs = new MutablePropertyValues();
        if (schedulerContext != null) {
            pvs.addPropertyValues(this.schedulerContext);
        }
        pvs.addPropertyValues(bundle.getJobDetail().getJobDataMap());
        pvs.addPropertyValues(bundle.getTrigger().getJobDataMap());
        if (this.ignoredUnknownProperties != null) {
            for (String propName : this.ignoredUnknownProperties) {
                if (pvs.contains(propName) && !bw.isWritableProperty(propName)) {
                    pvs.removePropertyValue(propName);
                }
            }
            bw.setPropertyValues(pvs);
        }
        else {
            bw.setPropertyValues(pvs, true);
        }
    }
}
项目:newtranx-utils    文件:SpringMybatisSetShardKeyAspect.java   
@Around("@annotation(com.newtranx.util.mysql.fabric.WithShardKey) || @within(com.newtranx.util.mysql.fabric.WithShardKey)")
public Object setShardKey(ProceedingJoinPoint pjp) throws Throwable {
    Method method = AspectJUtils.getMethod(pjp);
    String key = null;
    boolean force = method.getAnnotation(WithShardKey.class).force();
    int i = 0;
    for (Parameter p : method.getParameters()) {
        ShardKey a = p.getAnnotation(ShardKey.class);
        if (a != null) {
            if (key != null)
                throw new RuntimeException("found multiple shardkey");
            Object obj = pjp.getArgs()[i];
            if (StringUtils.isEmpty(a.property()))
                key = obj.toString();
            else {
                BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(obj);
                key = bw.getPropertyValue(a.property()).toString();
            }
        }
        i++;
    }
    if (key == null)
        throw new RuntimeException("can not find shardkey");
    fabricShardKey.set(key, force);
    return pjp.proceed();
}
项目:lodsve-framework    文件:RdbmsDataSourceBeanDefinitionBuilder.java   
private Map<String, String> toMap(Object object) {
    BeanWrapper wrapper = new BeanWrapperImpl(object);
    PropertyDescriptor[] descriptors = wrapper.getPropertyDescriptors();
    Map<String, String> properties = new HashMap<>(descriptors.length);
    for (PropertyDescriptor d : descriptors) {
        if (d.getWriteMethod() == null) {
            continue;
        }

        String name = d.getName();
        Object value = wrapper.getPropertyValue(name);

        properties.put(name, value.toString());
    }

    return properties;
}
项目:lodsve-framework    文件:PropertiesConfigurationFactory.java   
private void generateObject(String prefix, Object target) {
    BeanWrapper beanWrapper = new BeanWrapperImpl(target);

    PropertyDescriptor[] descriptors = beanWrapper.getPropertyDescriptors();
    for (PropertyDescriptor descriptor : descriptors) {
        if (descriptor.getWriteMethod() == null) {
            continue;
        }

        String name = descriptor.getName();
        Class<?> type = descriptor.getPropertyType();
        Method readMethod = descriptor.getReadMethod();
        TypeDescriptor typeDescriptor = beanWrapper.getPropertyTypeDescriptor(name);
        Required required = typeDescriptor.getAnnotation(Required.class);

        Object value = getValue(type, prefix, name, readMethod);

        if (value != null) {
            beanWrapper.setPropertyValue(name, value);
        } else if (required != null) {
            throw new RuntimeException(String.format("property [%s]'s value can't be null!please check your config!", name));
        }
    }
}
项目:eet.osslite.cz    文件:DaoSupport.java   
public void persist(Object entity) {
    // ReflectionUtils.
    BeanWrapper instance = new BeanWrapperImpl(entity);
    try {
        Object obj = instance.getPropertyValue("identification");
        if (obj == null) {
            instance.setPropertyValue("identification", new Identification());
            obj = instance.getPropertyValue("identification");
        }
        if (obj instanceof Identification) {
            Identification ident = (Identification) obj;
            ident.setCreated(new Date());
        }
    } catch (Exception e) {
        log.warn(e.getMessage());
    }
    em.persist(entity);
}
项目:spring4-understanding    文件:TaskExecutorFactoryBean.java   
@Override
public void afterPropertiesSet() throws Exception {
    BeanWrapper bw = new BeanWrapperImpl(ThreadPoolTaskExecutor.class);
    determinePoolSizeRange(bw);
    if (this.queueCapacity != null) {
        bw.setPropertyValue("queueCapacity", this.queueCapacity);
    }
    if (this.keepAliveSeconds != null) {
        bw.setPropertyValue("keepAliveSeconds", this.keepAliveSeconds);
    }
    if (this.rejectedExecutionHandler != null) {
        bw.setPropertyValue("rejectedExecutionHandler", this.rejectedExecutionHandler);
    }
    if (this.beanName != null) {
        bw.setPropertyValue("threadNamePrefix", this.beanName + "-");
    }
    this.target = (TaskExecutor) bw.getWrappedInstance();
    if (this.target instanceof InitializingBean) {
        ((InitializingBean) this.target).afterPropertiesSet();
    }
}
项目:spring4-understanding    文件:TilesConfigurer.java   
@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);
    }
}
项目:spring-content    文件:BeanUtils.java   
public static Object getFieldWithAnnotation(Object domainObj, Class<? extends Annotation> annotationClass)
        throws SecurityException, BeansException {
    Object value = null;

       Field field = findFieldWithAnnotation(domainObj, annotationClass);
       if (field != null && field.getAnnotation(annotationClass) != null) {
           try {
               PropertyDescriptor descriptor = org.springframework.beans.BeanUtils.getPropertyDescriptor(domainObj.getClass(), field.getName());
               if (descriptor != null) {
                   BeanWrapper wrapper = new BeanWrapperImpl(domainObj);
                   value = wrapper.getPropertyValue(field.getName());
               } else {
                   value = ReflectionUtils.getField(field, domainObj);
               }
               return value;
           } catch (IllegalArgumentException iae) {}
       }

    return value;
}
项目:spring4-understanding    文件:TilesConfigurer.java   
@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);
    }
}
项目:spring4-understanding    文件:StandardJmsActivationSpecFactory.java   
/**
 * Apply the specified acknowledge mode to the ActivationSpec object.
 * <p>This implementation applies the standard JCA 1.5 acknowledge modes
 * "Auto-acknowledge" and "Dups-ok-acknowledge". It throws an exception in
 * case of {@code CLIENT_ACKNOWLEDGE} or {@code SESSION_TRANSACTED}
 * having been requested.
 * @param bw the BeanWrapper wrapping the ActivationSpec object
 * @param ackMode the configured acknowledge mode
 * (according to the constants in {@link javax.jms.Session}
 * @see javax.jms.Session#AUTO_ACKNOWLEDGE
 * @see javax.jms.Session#DUPS_OK_ACKNOWLEDGE
 * @see javax.jms.Session#CLIENT_ACKNOWLEDGE
 * @see javax.jms.Session#SESSION_TRANSACTED
 */
protected void applyAcknowledgeMode(BeanWrapper bw, int ackMode) {
    if (ackMode == Session.SESSION_TRANSACTED) {
        throw new IllegalArgumentException("No support for SESSION_TRANSACTED: Only \"Auto-acknowledge\" " +
                "and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
    }
    else if (ackMode == Session.CLIENT_ACKNOWLEDGE) {
        throw new IllegalArgumentException("No support for CLIENT_ACKNOWLEDGE: Only \"Auto-acknowledge\" " +
                "and \"Dups-ok-acknowledge\" supported in standard JCA 1.5");
    }
    else if (bw.isWritableProperty("acknowledgeMode")) {
        bw.setPropertyValue("acknowledgeMode",
                ackMode == Session.DUPS_OK_ACKNOWLEDGE ? "Dups-ok-acknowledge" : "Auto-acknowledge");
    }
    else if (ackMode == Session.DUPS_OK_ACKNOWLEDGE) {
        // Standard JCA 1.5 "acknowledgeMode" apparently not supported (e.g. WebSphere MQ 6.0.2.1)
        throw new IllegalArgumentException(
                "Dups-ok-acknowledge not supported by underlying provider: " + this.activationSpecClass.getName());
    }
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
@Override
public Object configureBean(Object existingBean, String beanName) throws BeansException {
    markBeanAsCreated(beanName);
    BeanDefinition mbd = getMergedBeanDefinition(beanName);
    RootBeanDefinition bd = null;
    if (mbd instanceof RootBeanDefinition) {
        RootBeanDefinition rbd = (RootBeanDefinition) mbd;
        bd = (rbd.isPrototype() ? rbd : rbd.cloneBeanDefinition());
    }
    if (!mbd.isPrototype()) {
        if (bd == null) {
            bd = new RootBeanDefinition(mbd);
        }
        bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
        bd.allowCaching = ClassUtils.isCacheSafe(ClassUtils.getUserClass(existingBean), getBeanClassLoader());
    }
    BeanWrapper bw = new BeanWrapperImpl(existingBean);
    initBeanWrapper(bw);
    populateBean(beanName, bd, bw);
    return initializeBean(beanName, existingBean, bd);
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                }
            }, getAccessControlContext());
        }
        else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}
项目:spring    文件:AnnotationBeanUtils.java   
/**
 * Copy the properties of the supplied {@link Annotation} to the supplied target bean.
 * Any properties defined in {@code excludedProperties} will not be copied.
 * <p>A specified value resolver may resolve placeholders in property values, for example.
 * @param ann the annotation to copy from
 * @param bean the bean instance to copy to
 * @param valueResolver a resolve to post-process String property values (may be {@code null})
 * @param excludedProperties the names of excluded properties, if any
 * @see org.springframework.beans.BeanWrapper
 */
public static void copyPropertiesToBean(Annotation ann, Object bean, StringValueResolver valueResolver, String... excludedProperties) {
    Set<String> excluded = new HashSet<String>(Arrays.asList(excludedProperties));
    Method[] annotationProperties = ann.annotationType().getDeclaredMethods();
    BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    for (Method annotationProperty : annotationProperties) {
        String propertyName = annotationProperty.getName();
        if (!excluded.contains(propertyName) && bw.isWritableProperty(propertyName)) {
            Object value = ReflectionUtils.invokeMethod(annotationProperty, ann);
            if (valueResolver != null && value instanceof String) {
                value = valueResolver.resolveStringValue((String) value);
            }
            bw.setPropertyValue(propertyName, value);
        }
    }
}
项目:spring4-understanding    文件:AbstractAutowireCapableBeanFactory.java   
/**
     * Fill in any missing property values with references to
     * other beans in this factory if autowire is set to "byName".
     * @param beanName the name of the bean we're wiring up.
     * Useful for debugging messages; not used functionally.
     * @param mbd bean definition to update through autowiring
     * @param bw BeanWrapper from which we can obtain information about the bean
     * @param pvs the PropertyValues to register wired objects with
     */
    protected void autowireByName(
            String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
//��ȡ��ǰbean��������
        String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
        for (String propertyName : propertyNames) {
            if (containsBean(propertyName)) {
                Object bean = getBean(propertyName);
                pvs.add(propertyName, bean);
                registerDependentBean(propertyName, beanName);
                if (logger.isDebugEnabled()) {
                    logger.debug("Added autowiring by name from bean name '" + beanName +
                            "' via property '" + propertyName + "' to bean named '" + propertyName + "'");
                }
            }
            else {
                if (logger.isTraceEnabled()) {
                    logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
                            "' by name: no matching bean found");
                }
            }
        }
    }
项目:springlets    文件:ConvertedDatatablesData.java   
private static Map<String, Object> convert(Object value, ConversionService conversionService) {

    BeanWrapper bean = new BeanWrapperImpl(value);
    PropertyDescriptor[] properties = bean.getPropertyDescriptors();
    Map<String, Object> convertedValue = new HashMap<>(properties.length);

    for (int i = 0; i < properties.length; i++) {
      String name = properties[i].getName();
      Object propertyValue = bean.getPropertyValue(name);
      if (propertyValue != null
          && conversionService.canConvert(propertyValue.getClass(), String.class)) {
        TypeDescriptor source = bean.getPropertyTypeDescriptor(name);
        String convertedPropertyValue =
            (String) conversionService.convert(propertyValue, source, TYPE_STRING);
        convertedValue.put(name, convertedPropertyValue);
      }
    }

    return convertedValue;
  }
项目:spring4-understanding    文件:PropertyPathFactoryBean.java   
@Override
public Object getObject() throws BeansException {
    BeanWrapper target = this.targetBeanWrapper;
    if (target != null) {
        if (logger.isWarnEnabled() && this.targetBeanName != null &&
                this.beanFactory instanceof ConfigurableBeanFactory &&
                ((ConfigurableBeanFactory) this.beanFactory).isCurrentlyInCreation(this.targetBeanName)) {
            logger.warn("Target bean '" + this.targetBeanName + "' is still in creation due to a circular " +
                    "reference - obtained value for property '" + this.propertyPath + "' may be outdated!");
        }
    }
    else {
        // Fetch prototype target bean...
        Object bean = this.beanFactory.getBean(this.targetBeanName);
        target = PropertyAccessorFactory.forBeanPropertyAccess(bean);
    }
    return target.getPropertyValue(this.propertyPath);
}
项目:spring4-understanding    文件:BeanInfoTests.java   
@Test
public void testComplexObject() {
    ValueBean bean = new ValueBean();
    BeanWrapper bw = new BeanWrapperImpl(bean);
    Integer value = new Integer(1);

    bw.setPropertyValue("value", value);
    assertEquals("value not set correctly", bean.getValue(), value);

    value = new Integer(2);
    bw.setPropertyValue("value", value.toString());
    assertEquals("value not converted", bean.getValue(), value);

    bw.setPropertyValue("value", null);
    assertNull("value not null", bean.getValue());

    bw.setPropertyValue("value", "");
    assertNull("value not converted to null", bean.getValue());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testComplexObject() {
    TestBean tb = new TestBean();
    String newName = "Rod";
    String tbString = "Kerry_34";

    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.registerCustomEditor(ITestBean.class, new TestBeanEditor());
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
    pvs.addPropertyValue(new PropertyValue("name", newName));
    pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
    pvs.addPropertyValue(new PropertyValue("spouse", tbString));
    bw.setPropertyValues(pvs);
    assertTrue("spouse is non-null", tb.getSpouse() != null);
    assertTrue("spouse name is Kerry and age is 34",
            tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testComplexObjectWithOldValueAccess() {
    TestBean tb = new TestBean();
    String newName = "Rod";
    String tbString = "Kerry_34";

    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.setExtractOldValueForEditor(true);
    bw.registerCustomEditor(ITestBean.class, new OldValueAccessingTestBeanEditor());
    MutablePropertyValues pvs = new MutablePropertyValues();
    pvs.addPropertyValue(new PropertyValue("age", new Integer(55)));
    pvs.addPropertyValue(new PropertyValue("name", newName));
    pvs.addPropertyValue(new PropertyValue("touchy", "valid"));
    pvs.addPropertyValue(new PropertyValue("spouse", tbString));

    bw.setPropertyValues(pvs);
    assertTrue("spouse is non-null", tb.getSpouse() != null);
    assertTrue("spouse name is Kerry and age is 34",
            tb.getSpouse().getName().equals("Kerry") && tb.getSpouse().getAge() == 34);
    ITestBean spouse = tb.getSpouse();

    bw.setPropertyValues(pvs);
    assertSame("Should have remained same object", spouse, tb.getSpouse());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testCustomEditorForSingleProperty() {
    TestBean tb = new TestBean();
    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.registerCustomEditor(String.class, "name", new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue("prefix" + text);
        }
    });
    bw.setPropertyValue("name", "value");
    bw.setPropertyValue("touchy", "value");
    assertEquals("prefixvalue", bw.getPropertyValue("name"));
    assertEquals("prefixvalue", tb.getName());
    assertEquals("value", bw.getPropertyValue("touchy"));
    assertEquals("value", tb.getTouchy());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testCustomEditorForAllStringProperties() {
    TestBean tb = new TestBean();
    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue("prefix" + text);
        }
    });
    bw.setPropertyValue("name", "value");
    bw.setPropertyValue("touchy", "value");
    assertEquals("prefixvalue", bw.getPropertyValue("name"));
    assertEquals("prefixvalue", tb.getName());
    assertEquals("prefixvalue", bw.getPropertyValue("touchy"));
    assertEquals("prefixvalue", tb.getTouchy());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testCustomEditorForSingleNestedProperty() {
    TestBean tb = new TestBean();
    tb.setSpouse(new TestBean());
    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.registerCustomEditor(String.class, "spouse.name", new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue("prefix" + text);
        }
    });
    bw.setPropertyValue("spouse.name", "value");
    bw.setPropertyValue("touchy", "value");
    assertEquals("prefixvalue", bw.getPropertyValue("spouse.name"));
    assertEquals("prefixvalue", tb.getSpouse().getName());
    assertEquals("value", bw.getPropertyValue("touchy"));
    assertEquals("value", tb.getTouchy());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testCustomEditorForAllNestedStringProperties() {
    TestBean tb = new TestBean();
    tb.setSpouse(new TestBean());
    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.registerCustomEditor(String.class, new PropertyEditorSupport() {
        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            setValue("prefix" + text);
        }
    });
    bw.setPropertyValue("spouse.name", "value");
    bw.setPropertyValue("touchy", "value");
    assertEquals("prefixvalue", bw.getPropertyValue("spouse.name"));
    assertEquals("prefixvalue", tb.getSpouse().getName());
    assertEquals("prefixvalue", bw.getPropertyValue("touchy"));
    assertEquals("prefixvalue", tb.getTouchy());
}
项目:spring    文件:AbstractAutowireCapableBeanFactory.java   
/**
 * Instantiate the given bean using its default constructor.
 * @param beanName the name of the bean
 * @param mbd the bean definition for the bean
 * @return BeanWrapper for the new instance
 */
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
    try {
        Object beanInstance;
        final BeanFactory parent = this;
        if (System.getSecurityManager() != null) {
            beanInstance = AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    return getInstantiationStrategy().instantiate(mbd, beanName, parent);
                }
            }, getAccessControlContext());
        }
        else {
            beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
        }
        BeanWrapper bw = new BeanWrapperImpl(beanInstance);
        initBeanWrapper(bw);
        return bw;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
    }
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testCharacterEditor() {
    CharBean cb = new CharBean();
    BeanWrapper bw = new BeanWrapperImpl(cb);

    bw.setPropertyValue("myChar", new Character('c'));
    assertEquals('c', cb.getMyChar());

    bw.setPropertyValue("myChar", "c");
    assertEquals('c', cb.getMyChar());

    bw.setPropertyValue("myChar", "\u0041");
    assertEquals('A', cb.getMyChar());

    bw.setPropertyValue("myChar", "\\u0022");
    assertEquals('"', cb.getMyChar());

    CharacterEditor editor = new CharacterEditor(false);
    editor.setAsText("M");
    assertEquals("M", editor.getAsText());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testCharacterEditorWithAllowEmpty() {
    CharBean cb = new CharBean();
    BeanWrapper bw = new BeanWrapperImpl(cb);
    bw.registerCustomEditor(Character.class, new CharacterEditor(true));

    bw.setPropertyValue("myCharacter", new Character('c'));
    assertEquals(new Character('c'), cb.getMyCharacter());

    bw.setPropertyValue("myCharacter", "c");
    assertEquals(new Character('c'), cb.getMyCharacter());

    bw.setPropertyValue("myCharacter", "\u0041");
    assertEquals(new Character('A'), cb.getMyCharacter());

    bw.setPropertyValue("myCharacter", " ");
    assertEquals(new Character(' '), cb.getMyCharacter());

    bw.setPropertyValue("myCharacter", "");
    assertNull(cb.getMyCharacter());
}
项目:spring4-understanding    文件:CustomEditorTests.java   
@Test
public void testConversionToOldCollections() throws PropertyVetoException {
    OldCollectionsBean tb = new OldCollectionsBean();
    BeanWrapper bw = new BeanWrapperImpl(tb);
    bw.registerCustomEditor(Vector.class, new CustomCollectionEditor(Vector.class));
    bw.registerCustomEditor(Hashtable.class, new CustomMapEditor(Hashtable.class));

    bw.setPropertyValue("vector", new String[] {"a", "b"});
    assertEquals(2, tb.getVector().size());
    assertEquals("a", tb.getVector().get(0));
    assertEquals("b", tb.getVector().get(1));

    bw.setPropertyValue("hashtable", Collections.singletonMap("foo", "bar"));
    assertEquals(1, tb.getHashtable().size());
    assertEquals("bar", tb.getHashtable().get("foo"));
}
项目:nbone    文件:NamedJdbcDao.java   
@Override
public Object add(Object object) {
    SqlModel<Object> sqlModel = sqlBuilder.insertSelectiveSql(object);
    checkSqlModel(sqlModel);

    SqlParameterSource paramSource =  new BeanPropertySqlParameterSource(object);
    KeyHolder generatedKeyHolder =  new  GeneratedKeyHolder();
    namedPjdbcTemplate.update(sqlModel.getSql(), paramSource, generatedKeyHolder);
    Number num = generatedKeyHolder.getKey();

    String[] primaryKeys = sqlModel.getPrimaryKeys();
    if(primaryKeys != null && primaryKeys.length > 0){
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);
        beanWrapper.setPropertyValue(primaryKeys[0], num);
    }

    return object;
}