Java Code Examples for org.springframework.beans.MutablePropertyValues#addPropertyValue()

The following examples show how to use org.springframework.beans.MutablePropertyValues#addPropertyValue() . 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: MethodMapInterceptorsParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void registerCachingInterceptor(String cachingInterceptorId,
    BeanDefinitionRegistry registry,
    CacheSetupStrategyPropertySource propertySource) {

  MutablePropertyValues propertyValues = new MutablePropertyValues();

  RootBeanDefinition cachingInterceptor = new RootBeanDefinition(
      MethodMapCachingInterceptor.class, propertyValues);

  propertyValues.addPropertyValue(propertySource
      .getCacheKeyGeneratorProperty());
  propertyValues.addPropertyValue(propertySource
      .getCacheProviderFacadeProperty());
  propertyValues.addPropertyValue(propertySource
      .getCachingListenersProperty());
  propertyValues.addPropertyValue(propertySource.getCachingModelsProperty());

  registry.registerBeanDefinition(cachingInterceptorId, cachingInterceptor);
}
 
Example 2
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 3
Source File: DataBinderFieldAccessTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void bindingNoErrors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	assertTrue(binder.isIgnoreUnknownFields());
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", new Integer(32)));
	pvs.addPropertyValue(new PropertyValue("nonExisting", "someValue"));

	binder.bind(pvs);
	binder.close();

	assertTrue("changed name correctly", rod.getName().equals("Rod"));
	assertTrue("changed age correctly", rod.getAge() == 32);

	Map<?, ?> m = binder.getBindingResult().getModel();
	assertTrue("There is one element in map", m.size() == 2);
	FieldAccessBean tb = (FieldAccessBean) m.get("person");
	assertTrue("Same object", tb.equals(rod));
}
 
Example 4
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testExtensiveCircularReference() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	for (int i = 0; i < 1000; i++) {
		MutablePropertyValues pvs = new MutablePropertyValues();
		pvs.addPropertyValue(new PropertyValue("spouse", new RuntimeBeanReference("bean" + (i < 99 ? i + 1 : 0))));
		RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
		bd.setPropertyValues(pvs);
		lbf.registerBeanDefinition("bean" + i, bd);
	}
	lbf.preInstantiateSingletons();
	for (int i = 0; i < 1000; i++) {
		TestBean bean = (TestBean) lbf.getBean("bean" + i);
		TestBean otherBean = (TestBean) lbf.getBean("bean" + (i < 99 ? i + 1 : 0));
		assertTrue(bean.getSpouse() == otherBean);
	}
}
 
Example 5
Source File: DefaultListableBeanFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testAutowireWithUnsatisfiedConstructorDependency() {
	DefaultListableBeanFactory lbf = new DefaultListableBeanFactory();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	RootBeanDefinition bd = new RootBeanDefinition(TestBean.class);
	bd.setPropertyValues(pvs);
	lbf.registerBeanDefinition("rod", bd);
	assertEquals(1, lbf.getBeanDefinitionCount());
	try {
		lbf.autowire(UnsatisfiedConstructorDependency.class, AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR, true);
		fail("Should have unsatisfied constructor dependency on SideEffectBean");
	}
	catch (UnsatisfiedDependencyException ex) {
		// expected
	}
}
 
Example 6
Source File: BeanDefinitionDtoConverterServiceImpl.java    From geomajas-project-server with GNU Affero General Public License v3.0 6 votes vote down vote up
private BeanDefinition createBeanDefinitionByIntrospection(Object object, NamedBeanMap refs,
		ConversionService conversionService) {
	validate(object);
	GenericBeanDefinition def = new GenericBeanDefinition();
	def.setBeanClass(object.getClass());
	MutablePropertyValues propertyValues = new MutablePropertyValues();
	for (PropertyDescriptor descriptor : BeanUtils.getPropertyDescriptors(object.getClass())) {
		if (descriptor.getWriteMethod() != null) {
			try {
				Object value = descriptor.getReadMethod().invoke(object, (Object[]) null);
				if (value != null) {
					if ("id".equals(descriptor.getName())) {

					} else {
						propertyValues.addPropertyValue(descriptor.getName(),
								createMetadataElementByIntrospection(value, refs, conversionService));
					}
				}
			} catch (Exception e) {
				// our contract says to ignore this property
			}
		}
	}
	def.setPropertyValues(propertyValues);
	return def;
}
 
Example 7
Source File: AbstractCacheProviderFacadeParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Parses the specified XML element which contains the properties of the
 * <code>{@link org.springmodules.cache.provider.CacheProviderFacade}</code>
 * to register in the given registry of bean definitions.
 * 
 * @param element
 *          the XML element to parse
 * @param parserContext
 *          the parser context
 * @throws IllegalStateException
 *           if the value of the property <code>serializableFactory</code>
 *           is not equal to "NONE" or "XSTREAM"
 * 
 * @see BeanDefinitionParser#parse(Element, ParserContext)
 */
public final BeanDefinition parse(Element element, ParserContext parserContext)
    throws IllegalStateException {
  String id = element.getAttribute("id");

  // create the cache provider facade
  Class clazz = getCacheProviderFacadeClass();
  MutablePropertyValues propertyValues = new MutablePropertyValues();
  RootBeanDefinition cacheProviderFacade = new RootBeanDefinition(clazz,
      propertyValues);
  propertyValues.addPropertyValue(parseFailQuietlyEnabledProperty(element));
  propertyValues.addPropertyValue(parseSerializableFactoryProperty(element));

  BeanDefinitionRegistry registry = parserContext.getRegistry();
  registry.registerBeanDefinition(id, cacheProviderFacade);

  doParse(id, element, registry);
  return null;
}
 
Example 8
Source File: CustomEditorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 9
Source File: ReloadingPropertyPlaceholderConfigurer.java    From disconf with Apache License 2.0 5 votes vote down vote up
protected void visitPropertyValues(MutablePropertyValues pvs) {
    PropertyValue[] pvArray = pvs.getPropertyValues();
    for (PropertyValue pv : pvArray) {
        currentPropertyName = pv.getName();
        try {
            Object newVal = resolveValue(pv.getValue());
            if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) {
                pvs.addPropertyValue(pv.getName(), newVal);
            }
        } finally {
            currentPropertyName = null;
        }
    }
}
 
Example 10
Source File: BeanPostProcessorRegister.java    From brpc-java with Apache License 2.0 5 votes vote down vote up
@Override
public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,
                                    BeanDefinitionRegistry registry) {
    GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
    beanDefinition.setBeanClass(CommonAnnotationBeanPostProcessor.class);
    beanDefinition.setSynthetic(true);
    MutablePropertyValues values = new MutablePropertyValues();
    values.addPropertyValue("callback", new SpringBootAnnotationResolver());
    beanDefinition.setPropertyValues(values);
    registry.registerBeanDefinition("commonAnnotationBeanPostProcessor", beanDefinition);
}
 
Example 11
Source File: DataBinderFieldAccessTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void nestedBindingWithDisabledAutoGrow() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	binder.setAutoGrowNestedPaths(false);
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("spouse.name", "Kerry"));

	assertThatExceptionOfType(NullValueInNestedPathException.class).isThrownBy(() ->
			binder.bind(pvs));
}
 
Example 12
Source File: AnnotationsParser.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Registers a <code>{@link AnnotationFlushingAttributeSource}</code> and
 * adds it as a property of the flushing interceptor.
 * 
 * @param propertyValues
 *          the set of properties of the caching interceptor
 * @param registry
 *          the registry of bean definitions
 * 
 * @see AbstractMetadataAttributesParser#configureFlushingInterceptor(MutablePropertyValues,
 *      BeanDefinitionRegistry)
 */
@Override
protected void configureFlushingInterceptor(
    MutablePropertyValues propertyValues, BeanDefinitionRegistry registry) {

  String beanName = AnnotationFlushingAttributeSource.class.getName();

  registry.registerBeanDefinition(beanName, new RootBeanDefinition(
      AnnotationFlushingAttributeSource.class));

  propertyValues.addPropertyValue("flushingAttributeSource",
      new RuntimeBeanReference(beanName));
}
 
Example 13
Source File: ConfigurationBeanFactoryPostProcessor.java    From conf4j with MIT License 5 votes vote down vote up
private void replaceBeanWithInstrumentedClass(BeanDefinition definition, Class<?> configurationType) {
    definition.setBeanClassName(ConfigurationFactoryBean.class.getName());
    MutablePropertyValues propertyValues = definition.getPropertyValues();
    propertyValues.addPropertyValue("configurationFactory", new RuntimeBeanReference(CONF4J_CONFIGURATION_FACTORY));
    propertyValues.addPropertyValue("configurationSource", new RuntimeBeanReference(CONF4J_CONFIGURATION_SOURCE));
    propertyValues.addPropertyValue("configurationType", configurationType);
}
 
Example 14
Source File: DataBinderFieldAccessTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void bindingWithErrors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", "32x"));
	binder.bind(pvs);

	try {
		binder.close();
		fail("Should have thrown BindException");
	}
	catch (BindException ex) {
		assertTrue("changed name correctly", rod.getName().equals("Rod"));
		//assertTrue("changed age correctly", rod.getAge() == 32);

		Map<?, ?> map = binder.getBindingResult().getModel();
		//assertTrue("There are 3 element in map", m.size() == 1);
		FieldAccessBean tb = (FieldAccessBean) map.get("person");
		assertTrue("Same object", tb.equals(rod));

		BindingResult br = (BindingResult) map.get(BindingResult.MODEL_KEY_PREFIX + "person");
		assertTrue("Added itself to map", br == binder.getBindingResult());
		assertTrue(br.hasErrors());
		assertTrue("Correct number of errors", br.getErrorCount() == 1);

		assertTrue("Has age errors", br.hasFieldErrors("age"));
		assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1);
		assertEquals("32x", binder.getBindingResult().getFieldValue("age"));
		assertEquals("32x", binder.getBindingResult().getFieldError("age").getRejectedValue());
		assertEquals(0, tb.getAge());
	}
}
 
Example 15
Source File: ReloadingPropertyPlaceholderConfigurer.java    From disconf with Apache License 2.0 5 votes vote down vote up
protected void visitPropertyValues(MutablePropertyValues pvs) {
    PropertyValue[] pvArray = pvs.getPropertyValues();
    for (PropertyValue pv : pvArray) {
        currentPropertyName = pv.getName();
        try {
            Object newVal = resolveValue(pv.getValue());
            if (!ObjectUtils.nullSafeEquals(newVal, pv.getValue())) {
                pvs.addPropertyValue(pv.getName(), newVal);
            }
        } finally {
            currentPropertyName = null;
        }
    }
}
 
Example 16
Source File: DataBinderFieldAccessTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void nestedBindingWithDisabledAutoGrow() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	binder.setAutoGrowNestedPaths(false);
	binder.initDirectFieldAccess();
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("spouse.name", "Kerry"));

	thrown.expect(NullValueInNestedPathException.class);
	binder.bind(pvs);
}
 
Example 17
Source File: DispatcherServletTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void detectHandlerMappingFromParent() throws ServletException, IOException {
	// create a parent context that includes a mapping
	StaticWebApplicationContext parent = new StaticWebApplicationContext();
	parent.setServletContext(getServletContext());
	parent.registerSingleton("parentHandler", ControllerFromParent.class, new MutablePropertyValues());

	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("mappings", URL_KNOWN_ONLY_PARENT + "=parentHandler"));

	parent.registerSingleton("parentMapping", SimpleUrlHandlerMapping.class, pvs);
	parent.refresh();

	DispatcherServlet complexDispatcherServlet = new DispatcherServlet();
	// will have parent
	complexDispatcherServlet.setContextClass(ComplexWebApplicationContext.class);
	complexDispatcherServlet.setNamespace("test");

	ServletConfig config = new MockServletConfig(getServletContext(), "complex");
	config.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, parent);
	complexDispatcherServlet.init(config);

	MockHttpServletRequest request = new MockHttpServletRequest(getServletContext(), "GET", URL_KNOWN_ONLY_PARENT);
	MockHttpServletResponse response = new MockHttpServletResponse();
	complexDispatcherServlet.service(request, response);

	assertFalse("Matched through parent controller/handler pair: not response=" + response.getStatus(),
			response.getStatus() == HttpServletResponse.SC_NOT_FOUND);
}
 
Example 18
Source File: DataBinderFieldAccessTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void bindingWithErrorsAndCustomEditors() throws Exception {
	FieldAccessBean rod = new FieldAccessBean();
	DataBinder binder = new DataBinder(rod, "person");
	binder.initDirectFieldAccess();
	binder.registerCustomEditor(TestBean.class, "spouse", new PropertyEditorSupport() {
		@Override
		public void setAsText(String text) throws IllegalArgumentException {
			setValue(new TestBean(text, 0));
		}
		@Override
		public String getAsText() {
			return ((TestBean) getValue()).getName();
		}
	});
	MutablePropertyValues pvs = new MutablePropertyValues();
	pvs.addPropertyValue(new PropertyValue("name", "Rod"));
	pvs.addPropertyValue(new PropertyValue("age", "32x"));
	pvs.addPropertyValue(new PropertyValue("spouse", "Kerry"));
	binder.bind(pvs);

	try {
		binder.close();
		fail("Should have thrown BindException");
	}
	catch (BindException ex) {
		assertTrue("changed name correctly", rod.getName().equals("Rod"));
		//assertTrue("changed age correctly", rod.getAge() == 32);

		Map<?, ?> model = binder.getBindingResult().getModel();
		//assertTrue("There are 3 element in map", m.size() == 1);
		FieldAccessBean tb = (FieldAccessBean) model.get("person");
		assertTrue("Same object", tb.equals(rod));

		BindingResult br = (BindingResult) model.get(BindingResult.MODEL_KEY_PREFIX + "person");
		assertTrue("Added itself to map", br == binder.getBindingResult());
		assertTrue(br.hasErrors());
		assertTrue("Correct number of errors", br.getErrorCount() == 1);

		assertTrue("Has age errors", br.hasFieldErrors("age"));
		assertTrue("Correct number of age errors", br.getFieldErrorCount("age") == 1);
		assertEquals("32x", binder.getBindingResult().getFieldValue("age"));
		assertEquals("32x", binder.getBindingResult().getFieldError("age").getRejectedValue());
		assertEquals(0, tb.getAge());

		assertTrue("Does not have spouse errors", !br.hasFieldErrors("spouse"));
		assertEquals("Kerry", binder.getBindingResult().getFieldValue("spouse"));
		assertNotNull(tb.getSpouse());
	}
}
 
Example 19
Source File: RpcAnnotationResolver.java    From brpc-java with Apache License 2.0 4 votes vote down vote up
/**
 * Creates the rpc proxy factory bean.
 *
 * @param rpcProxy         the rpc proxy
 * @param beanFactory      the bean factory
 * @param rpcClientOptions the rpc client options
 * @param namingServiceUrl naming service url
 * @return the rpc proxy factory bean
 */
protected RpcProxyFactoryBean createRpcProxyFactoryBean(RpcProxy rpcProxy,
                                                        Class serviceInterface,
                                                        DefaultListableBeanFactory beanFactory,
                                                        RpcClientOptions rpcClientOptions,
                                                        String namingServiceUrl) {
    GenericBeanDefinition beanDef = new GenericBeanDefinition();
    beanDef.setBeanClass(RpcProxyFactoryBean.class);
    MutablePropertyValues values = new MutablePropertyValues();
    for (Field field : rpcClientOptions.getClass().getDeclaredFields()) {
        try {
            if (field.getType().equals(Logger.class)) {
                // ignore properties of org.slf4j.Logger class
                continue;
            }
            field.setAccessible(true);
            values.addPropertyValue(field.getName(), field.get(rpcClientOptions));
        } catch (Exception ex) {
            LOGGER.warn("field not exist:", ex);
        }
    }
    values.addPropertyValue("serviceInterface", serviceInterface);
    values.addPropertyValue("namingServiceUrl", namingServiceUrl);
    values.addPropertyValue("group", rpcProxy.group());
    values.addPropertyValue("version", rpcProxy.version());
    values.addPropertyValue("ignoreFailOfNamingService", rpcProxy.ignoreFailOfNamingService());
    values.addPropertyValue("serviceId", rpcProxy.name());

    // interceptor
    String interceptorNames = parsePlaceholder(rpcProxy.interceptorBeanNames());
    if (!StringUtils.isBlank(interceptorNames)) {
        List<Interceptor> customInterceptors = new ArrayList<Interceptor>();
        String[] interceptorNameArray = interceptorNames.split(",");
        for (String interceptorName : interceptorNameArray) {
            Interceptor interceptor = beanFactory.getBean(interceptorName, Interceptor.class);
            customInterceptors.add(interceptor);
        }
        values.addPropertyValue("interceptors", customInterceptors);
    } else {
        values.addPropertyValue("interceptors", interceptors);
    }

    beanDef.setPropertyValues(values);
    String serviceInterfaceBeanName = serviceInterface.getSimpleName();
    beanFactory.registerBeanDefinition(serviceInterfaceBeanName, beanDef);
    return beanFactory.getBean("&" + serviceInterfaceBeanName, RpcProxyFactoryBean.class);
}
 
Example 20
Source File: CacheSetupStrategyPropertySource.java    From cacheonix-core with GNU Lesser General Public License v2.1 3 votes vote down vote up
/**
 * Returns the properties specified by:
 * <ul>
 * <li><code>{@link #getCacheProviderFacadeProperty()}</code></li>
 * <li><code>{@link #getCachingListenersProperty()}</code></li>
 * <li><code>{@link #getCachingModelsProperty()}</code></li>
 * <li><code>{@link #getFlushingModelsProperty()}</code></li>
 * </ul>
 * 
 * @return all the properties stored in this object.
 */
public MutablePropertyValues getAllProperties() {
  MutablePropertyValues allPropertyValues = new MutablePropertyValues();
  allPropertyValues.addPropertyValue(getCacheKeyGeneratorProperty());
  allPropertyValues.addPropertyValue(getCacheProviderFacadeProperty());
  allPropertyValues.addPropertyValue(getCachingListenersProperty());
  allPropertyValues.addPropertyValue(getCachingModelsProperty());
  allPropertyValues.addPropertyValue(getFlushingModelsProperty());

  return allPropertyValues;
}