下面列出了org.springframework.beans.MutablePropertyValues#addPropertyValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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());
}
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);
}
/**
* 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;
}
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;
}
@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
}
}
@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);
}
}
@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));
}
@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);
}
@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));
}
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;
}
}
}
@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);
}
/**
* 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));
}
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);
}
@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());
}
}
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;
}
}
}
@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);
}
@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);
}
/**
* 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);
}
@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());
}
}
/**
* 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;
}