org.springframework.beans.PropertyAccessorFactory#forBeanPropertyAccess ( )源码实例Demo

下面列出了org.springframework.beans.PropertyAccessorFactory#forBeanPropertyAccess ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: 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);
}
 
源代码2 项目: jdal   文件: CompositeBinder.java
public void autobind(Object view) {
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(getModel());
	PropertyAccessor  viewPropertyAccessor = new DirectFieldAccessor(view);
	// iterate on model properties
	for (PropertyDescriptor pd : bw.getPropertyDescriptors()) {
		String propertyName = pd.getName();
		if ( !ignoredProperties.contains(propertyName) && viewPropertyAccessor.isReadableProperty(propertyName)) {
			Object control = viewPropertyAccessor.getPropertyValue(propertyName);
			if (control != null) {
				if (log.isDebugEnabled()) 
					log.debug("Found control: " + control.getClass().getSimpleName() + 
							" for property: " + propertyName);
				bind(control, propertyName);
			}
		}
	}
}
 
@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;
}
 
@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);
}
 
private void writeObjectEntry(TagWriter tagWriter, @Nullable String valueProperty,
		@Nullable String labelProperty, Object item, int itemIndex) throws JspException {

	BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(item);
	Object renderValue;
	if (valueProperty != null) {
		renderValue = wrapper.getPropertyValue(valueProperty);
	}
	else if (item instanceof Enum) {
		renderValue = ((Enum<?>) item).name();
	}
	else {
		renderValue = item;
	}
	Object renderLabel = (labelProperty != null ? wrapper.getPropertyValue(labelProperty) : item);
	writeElementTag(tagWriter, item, renderValue, renderLabel, itemIndex);
}
 
源代码6 项目: java-technology-stack   文件: TilesConfigurer.java
@Override
protected DefinitionsFactory createDefinitionsFactory(ApplicationContext applicationContext,
		LocaleResolver resolver) {

	if (definitionsFactoryClass != null) {
		DefinitionsFactory factory = BeanUtils.instantiateClass(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);
	}
}
 
源代码7 项目: jdal   文件: ListTableModel.java
/**
 * {@inheritDoc}
 */
public void setValueAt(Object value, int rowIndex, int columnIndex) {
	if (isCheckColum(columnIndex)) {
		checks.set(rowIndex, (Boolean) value);
		// sync selectedRowSet
		Object row = list.get(rowIndex);

		if (Boolean.TRUE.equals(value))
			selectedRowSet.add((Serializable) getPrimaryKey(row));
		else
			selectedRowSet.remove(getPrimaryKey(row));

	}
	else if (isPropertyColumn(columnIndex)) {
		int index = columnToPropertyIndex(columnIndex);
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(list.get(rowIndex));
		bw.setPropertyValue(columnNames.get(index), value);
		fireTableCellUpdated(rowIndex, columnIndex);
	}
}
 
源代码8 项目: syncope   文件: AutowiringSpringBeanJobFactory.java
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle) throws Exception {
    Object job = beanFactory.getBean(bundle.getJobDetail().getKey().getName());
    if (isEligibleForPropertyPopulation(job)) {
        BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(job);
        MutablePropertyValues pvs = new MutablePropertyValues();
        if (this.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);
        }
    }
    return job;
}
 
/**
 * 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(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);
		}
	}
	return job;
}
 
源代码10 项目: mica   文件: BeanUtil.java
/**
 * 获取Bean的属性, 支持 propertyName 多级 :test.user.name
 *
 * @param bean         bean
 * @param propertyName 属性名
 * @return 属性值
 */
@Nullable
public static Object getProperty(@Nullable Object bean, String propertyName) {
	if (bean == null) {
		return null;
	}
	BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
	return beanWrapper.getPropertyValue(propertyName);
}
 
源代码11 项目: blog_demos   文件: PropertyPathFactoryBean.java
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	this.beanFactory = beanFactory;

	if (this.targetBeanWrapper != null && this.targetBeanName != null) {
		throw new IllegalArgumentException("Specify either 'targetObject' or 'targetBeanName', not both");
	}

	if (this.targetBeanWrapper == null && this.targetBeanName == null) {
		if (this.propertyPath != null) {
			throw new IllegalArgumentException(
					"Specify 'targetObject' or 'targetBeanName' in combination with 'propertyPath'");
		}

		// No other properties specified: check bean name.
		int dotIndex = this.beanName.indexOf('.');
		if (dotIndex == -1) {
			throw new IllegalArgumentException(
					"Neither 'targetObject' nor 'targetBeanName' specified, and PropertyPathFactoryBean " +
					"bean name '" + this.beanName + "' does not follow 'beanName.property' syntax");
		}
		this.targetBeanName = this.beanName.substring(0, dotIndex);
		this.propertyPath = this.beanName.substring(dotIndex + 1);
	}

	else if (this.propertyPath == null) {
		// either targetObject or targetBeanName specified
		throw new IllegalArgumentException("'propertyPath' is required");
	}

	if (this.targetBeanWrapper == null && this.beanFactory.isSingleton(this.targetBeanName)) {
		// Eagerly fetch singleton target bean, and determine result type.
		Object bean = this.beanFactory.getBean(this.targetBeanName);
		this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
		this.resultType = this.targetBeanWrapper.getPropertyType(this.propertyPath);
	}
}
 
private void writeMapEntry(TagWriter tagWriter, String valueProperty,
		String labelProperty, Map.Entry<?, ?> entry, int itemIndex) throws JspException {

	Object mapKey = entry.getKey();
	Object mapValue = entry.getValue();
	BeanWrapper mapKeyWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapKey);
	BeanWrapper mapValueWrapper = PropertyAccessorFactory.forBeanPropertyAccess(mapValue);
	Object renderValue = (valueProperty != null ?
			mapKeyWrapper.getPropertyValue(valueProperty) : mapKey.toString());
	Object renderLabel = (labelProperty != null ?
			mapValueWrapper.getPropertyValue(labelProperty) : mapValue.toString());
	writeElementTag(tagWriter, mapKey, renderValue, renderLabel, itemIndex);
}
 
源代码13 项目: spring-analysis-note   文件: HttpServletBean.java
/**
 * Map config parameters onto bean properties of this servlet, and
 * invoke subclass initialization.
 * @throws ServletException if bean properties are invalid (or required
 * properties are missing), or if subclass initialization fails.
 */
@Override
public final void init() throws ServletException {

	// Set bean properties from init parameters.
	// 解析 init-param 并封装到 pvs 变量中
	PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
	if (!pvs.isEmpty()) {
		try {
			// 将当前的这个 Servlet 类转换为一个 BeanWrapper,从而能够以 Spring 的方式对 init—param 的值注入
			BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
			ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
			// 注册自定义属性编辑器,一旦遇到 Resource 类型的属性将会使用 ResourceEditor 进行解析
			bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
			// 空实现,留给子类覆盖
			initBeanWrapper(bw);
			bw.setPropertyValues(pvs, true);
		}
		catch (BeansException ex) {
			if (logger.isErrorEnabled()) {
				logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
			}
			throw ex;
		}
	}

	// Let subclasses do whatever initialization they like.
	// 初始化 servletBean (让子类实现,这里它的实现子类是 FrameworkServlet)
	initServletBean();
}
 
源代码14 项目: ecs-sync   文件: ConfigWrapper.java
public C parse(CommandLine commandLine, String prefix) {
    try {
        C object = getTargetClass().newInstance();
        BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(object);

        for (String name : propertyNames()) {
            ConfigPropertyWrapper propertyWrapper = getPropertyWrapper(name);
            if (!propertyWrapper.isCliOption()) continue;

            org.apache.commons.cli.Option option = propertyWrapper.getCliOption(prefix);

            if (commandLine.hasOption(option.getLongOpt())) {

                Object value = commandLine.getOptionValue(option.getLongOpt());
                if (propertyWrapper.getDescriptor().getPropertyType().isArray())
                    value = commandLine.getOptionValues(option.getLongOpt());

                if (Boolean.class == propertyWrapper.getDescriptor().getPropertyType()
                        || "boolean".equals(propertyWrapper.getDescriptor().getPropertyType().getName()))
                    value = Boolean.toString(!propertyWrapper.isCliInverted());

                beanWrapper.setPropertyValue(name, value);
            }
        }

        return object;
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}
 
源代码15 项目: onetwo   文件: BeanWrapperTest.java
@Test
	public void testMap(){
		UserData u = new UserData();
		bw = PropertyAccessorFactory.forBeanPropertyAccess(u);
//		bw = SpringUtils.newBeanWrapper(u);
		bw.setAutoGrowNestedPaths(true);
		
		bw.setPropertyValue("attrs[id]", "11");
		Assert.assertEquals(u.getAttrs().get("id"), "11");
		
		try {
			bw.setPropertyValue("attrs.id2", "11");
			Assert.fail("must be fail!");
		} catch (Exception e) {
			Assert.assertNotNull(e);
		}
		
		Map<String, String> attrs = LangUtils.newHashMap();
		/*bw = SpringUtils.newBeanWrapper(attrs);
		bw.setAutoGrowNestedPaths(true);
		try {
			bw.setPropertyValue("id", "11");
			Assert.fail();
		} catch (Exception e) {
		}*/
		bw = SpringUtils.newBeanMapWrapper(attrs);
		bw.setPropertyValue("id", "11");
		Assert.assertEquals(attrs.get("id"), "11");
		
	}
 
源代码16 项目: lams   文件: PropertyPathFactoryBean.java
@Override
public void setBeanFactory(BeanFactory beanFactory) {
	this.beanFactory = beanFactory;

	if (this.targetBeanWrapper != null && this.targetBeanName != null) {
		throw new IllegalArgumentException("Specify either 'targetObject' or 'targetBeanName', not both");
	}

	if (this.targetBeanWrapper == null && this.targetBeanName == null) {
		if (this.propertyPath != null) {
			throw new IllegalArgumentException(
					"Specify 'targetObject' or 'targetBeanName' in combination with 'propertyPath'");
		}

		// No other properties specified: check bean name.
		int dotIndex = this.beanName.indexOf('.');
		if (dotIndex == -1) {
			throw new IllegalArgumentException(
					"Neither 'targetObject' nor 'targetBeanName' specified, and PropertyPathFactoryBean " +
					"bean name '" + this.beanName + "' does not follow 'beanName.property' syntax");
		}
		this.targetBeanName = this.beanName.substring(0, dotIndex);
		this.propertyPath = this.beanName.substring(dotIndex + 1);
	}

	else if (this.propertyPath == null) {
		// either targetObject or targetBeanName specified
		throw new IllegalArgumentException("'propertyPath' is required");
	}

	if (this.targetBeanWrapper == null && this.beanFactory.isSingleton(this.targetBeanName)) {
		// Eagerly fetch singleton target bean, and determine result type.
		Object bean = this.beanFactory.getBean(this.targetBeanName);
		this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(bean);
		this.resultType = this.targetBeanWrapper.getPropertyType(this.propertyPath);
	}
}
 
源代码17 项目: spring4-understanding   文件: GenericFilterBean.java
/**
 * Standard way of initializing this filter.
 * Map config parameters onto bean properties of this filter, and
 * invoke subclass initialization.
 * @param filterConfig the configuration for this filter
 * @throws ServletException if bean properties are invalid (or required
 * properties are missing), or if subclass initialization fails.
 * @see #initFilterBean
 */
@Override
public final void init(FilterConfig filterConfig) throws ServletException {
	Assert.notNull(filterConfig, "FilterConfig must not be null");
	if (logger.isDebugEnabled()) {
		logger.debug("Initializing filter '" + filterConfig.getFilterName() + "'");
	}

	this.filterConfig = filterConfig;

	// Set bean properties from init parameters.
	try {
		PropertyValues pvs = new FilterConfigPropertyValues(filterConfig, this.requiredProperties);
		BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
		ResourceLoader resourceLoader = new ServletContextResourceLoader(filterConfig.getServletContext());
		bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, this.environment));
		initBeanWrapper(bw);
		bw.setPropertyValues(pvs, true);
	}
	catch (BeansException ex) {
		String msg = "Failed to set bean properties on filter '" +
			filterConfig.getFilterName() + "': " + ex.getMessage();
		logger.error(msg, ex);
		throw new NestedServletException(msg, ex);
	}

	// Let subclasses do whatever initialization they like.
	initFilterBean();

	if (logger.isDebugEnabled()) {
		logger.debug("Filter '" + filterConfig.getFilterName() + "' configured successfully");
	}
}
 
源代码18 项目: jdal   文件: ListTableModel.java
private Object getCellValue(int rowIndex, int columnIndex) {
	BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(list.get(rowIndex));
	return bw.getPropertyValue(columnNames.get(columnIndex));
}
 
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 {
		// 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 (jobListenerName != 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);
}
 
/**
 * Specify a target object to apply the property path to.
 * Alternatively, specify a target bean name.
 * @param targetObject a target object, for example a bean reference
 * or an inner bean
 * @see #setTargetBeanName
 */
public void setTargetObject(Object targetObject) {
	this.targetBeanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(targetObject);
}