Java Code Examples for org.springframework.beans.BeanWrapper#setPropertyValue()

The following examples show how to use org.springframework.beans.BeanWrapper#setPropertyValue() . 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: 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 2
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testIndexedPropertiesWithListPropertyEditor() {
	IndexedTestBean bean = new IndexedTestBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			List<TestBean> result = new ArrayList<TestBean>();
			result.add(new TestBean("list" + text, 99));
			setValue(result);
		}
	});
	bw.setPropertyValue("list", "1");
	assertEquals("list1", ((TestBean) bean.getList().get(0)).getName());
	bw.setPropertyValue("list[0]", "test");
	assertEquals("test", bean.getList().get(0));
}
 
Example 3
Source File: StandardJmsActivationSpecFactory.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
	}
}
 
Example 4
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 5
Source File: AnnotationBeanUtils.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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);
		}
	}
}
 
Example 6
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 7
Source File: AnnotationBeanUtils.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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, @Nullable StringValueResolver valueResolver,
		String... excludedProperties) {

	Set<String> excluded = new HashSet<>(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);
		}
	}
}
 
Example 8
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testIndexedPropertiesWithListPropertyEditor() {
	IndexedTestBean bean = new IndexedTestBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	bw.registerCustomEditor(List.class, "list", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			List<TestBean> result = new ArrayList<>();
			result.add(new TestBean("list" + text, 99));
			setValue(result);
		}
	});
	bw.setPropertyValue("list", "1");
	assertEquals("list1", ((TestBean) bean.getList().get(0)).getName());
	bw.setPropertyValue("list[0]", "test");
	assertEquals("test", bean.getList().get(0));
}
 
Example 9
Source File: CustomEditorTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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());
}
 
Example 10
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testUninitializedArrayPropertyWithCustomEditor() {
	IndexedTestBean bean = new IndexedTestBean(false);
	BeanWrapper bw = new BeanWrapperImpl(bean);
	PropertyEditor pe = new CustomNumberEditor(Integer.class, true);
	bw.registerCustomEditor(null, "list.age", pe);
	TestBean tb = new TestBean();
	bw.setPropertyValue("list", new ArrayList<>());
	bw.setPropertyValue("list[0]", tb);
	assertEquals(tb, bean.getList().get(0));
	assertEquals(pe, bw.findCustomEditor(int.class, "list.age"));
	assertEquals(pe, bw.findCustomEditor(null, "list.age"));
	assertEquals(pe, bw.findCustomEditor(int.class, "list[0].age"));
	assertEquals(pe, bw.findCustomEditor(null, "list[0].age"));
}
 
Example 11
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testArrayToArrayConversion() throws PropertyVetoException {
	IndexedTestBean tb = new IndexedTestBean();
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(TestBean.class, new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue(new TestBean(text, 99));
		}
	});
	bw.setPropertyValue("array", new String[] {"a", "b"});
	assertEquals(2, tb.getArray().length);
	assertEquals("a", tb.getArray()[0].getName());
	assertEquals("b", tb.getArray()[1].getName());
}
 
Example 12
Source File: MyBeanUtils.java    From spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * 拷贝 source 中的属性到 target 中
 *
 * @param source
 * @param target
 * @param properties
 */
public static void copyBeanProperties(final Object source, final Object target, final Iterable<String> properties) {

    final BeanWrapper src = new BeanWrapperImpl(source);
    final BeanWrapper trg = new BeanWrapperImpl(target);

    for (final String propertyName : properties) {
        trg.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
    }

}
 
Example 13
Source File: MvcInterceptorManager.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected MvcInterceptor injectAnnotationProperties(MvcInterceptor interInst, MvcInterceptorMeta attr){
	List<PropertyAnnoMeta> properties = attr.getProperties();
	BeanWrapper bw = SpringUtils.newBeanWrapper(interInst);
	for(PropertyAnnoMeta prop : properties){
		bw.setPropertyValue(prop.getName(), prop.getValue());
	}
	return interInst;
}
 
Example 14
Source File: ConfigWrapper.java    From ecs-sync with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 15
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testCustomNumberEditorWithFrenchBigDecimal() throws Exception {
	NumberFormat nf = NumberFormat.getNumberInstance(Locale.FRENCH);
	NumberTestBean tb = new NumberTestBean();
	BeanWrapper bw = new BeanWrapperImpl(tb);
	bw.registerCustomEditor(BigDecimal.class, new CustomNumberEditor(BigDecimal.class, nf, true));
	bw.setPropertyValue("bigDecimal", "1000");
	assertEquals(1000.0f, tb.getBigDecimal().floatValue(), 0f);
	bw.setPropertyValue("bigDecimal", "1000,5");
	assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f);
	bw.setPropertyValue("bigDecimal", "1 000,5");
	assertEquals(1000.5f, tb.getBigDecimal().floatValue(), 0f);
}
 
Example 16
Source File: CustomEditorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testByteArrayPropertyEditor() {
	PrimitiveArrayBean bean = new PrimitiveArrayBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	bw.setPropertyValue("byteArray", "myvalue");
	assertEquals("myvalue", new String(bean.getByteArray()));
}
 
Example 17
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testDefaultBooleanEditorForWrapperType() {
	BooleanTestBean tb = new BooleanTestBean();
	BeanWrapper bw = new BeanWrapperImpl(tb);

	bw.setPropertyValue("bool2", "true");
	assertTrue("Correct bool2 value", Boolean.TRUE.equals(bw.getPropertyValue("bool2")));
	assertTrue("Correct bool2 value", tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "false");
	assertTrue("Correct bool2 value", Boolean.FALSE.equals(bw.getPropertyValue("bool2")));
	assertTrue("Correct bool2 value", !tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "on");
	assertTrue("Correct bool2 value", tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "off");
	assertTrue("Correct bool2 value", !tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "yes");
	assertTrue("Correct bool2 value", tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "no");
	assertTrue("Correct bool2 value", !tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "1");
	assertTrue("Correct bool2 value", tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "0");
	assertTrue("Correct bool2 value", !tb.getBool2().booleanValue());

	bw.setPropertyValue("bool2", "");
	assertNull("Correct bool2 value", tb.getBool2());
}
 
Example 18
Source File: DefaultJmsActivationSpecFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * This implementation supports Spring's extended "maxConcurrency"
 * and "prefetchSize" settings through detecting corresponding
 * ActivationSpec properties: "maxSessions"/"maxNumberOfWorks" and
 * "maxMessagesPerSessions"/"maxMessages", respectively
 * (following ActiveMQ's and JORAM's naming conventions).
 */
@Override
protected void populateActivationSpecProperties(BeanWrapper bw, JmsActivationSpecConfig config) {
	super.populateActivationSpecProperties(bw, config);
	if (config.getMaxConcurrency() > 0) {
		if (bw.isWritableProperty("maxSessions")) {
			// ActiveMQ
			bw.setPropertyValue("maxSessions", Integer.toString(config.getMaxConcurrency()));
		}
		else if (bw.isWritableProperty("maxNumberOfWorks")) {
			// JORAM
			bw.setPropertyValue("maxNumberOfWorks", Integer.toString(config.getMaxConcurrency()));
		}
		else if (bw.isWritableProperty("maxConcurrency")){
			// WebSphere
			bw.setPropertyValue("maxConcurrency", Integer.toString(config.getMaxConcurrency()));
		}
	}
	if (config.getPrefetchSize() > 0) {
		if (bw.isWritableProperty("maxMessagesPerSessions")) {
			// ActiveMQ
			bw.setPropertyValue("maxMessagesPerSessions", Integer.toString(config.getPrefetchSize()));
		}
		else if (bw.isWritableProperty("maxMessages")) {
			// JORAM
			bw.setPropertyValue("maxMessages", Integer.toString(config.getPrefetchSize()));
		}
		else if (bw.isWritableProperty("maxBatchSize")){
			// WebSphere
			bw.setPropertyValue("maxBatchSize", Integer.toString(config.getPrefetchSize()));
		}
	}
}
 
Example 19
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testByteArrayPropertyEditor() {
	PrimitiveArrayBean bean = new PrimitiveArrayBean();
	BeanWrapper bw = new BeanWrapperImpl(bean);
	bw.setPropertyValue("byteArray", "myvalue");
	assertEquals("myvalue", new String(bean.getByteArray()));
}
 
Example 20
Source File: BeanUtil.java    From mica with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * 设置Bean属性, 支持 propertyName 多级 :test.user.name
 *
 * @param bean         bean
 * @param propertyName 属性名
 * @param value        属性值
 */
public static void setProperty(Object bean, String propertyName, Object value) {
	BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(Objects.requireNonNull(bean, "bean Could not null"));
	beanWrapper.setPropertyValue(propertyName, value);
}