下面列出了怎么用org.springframework.beans.BeanWrapperImpl的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
public List getChildren(Object parent) {
List<Object> children = new ArrayList<>();
for (CrudRepository repo : repositories) {
String parentProp = null;
Iterable candidates = repo.findAll();
for (Object candidate : candidates) {
if (parentProp == null) {
parentProp = CmisServiceBridge.findParentProperty(candidate);
}
if (parentProp != null) {
BeanWrapper wrapper = new BeanWrapperImpl(candidate);
PropertyDescriptor descriptor = wrapper.getPropertyDescriptor(parentProp);
if (descriptor != null && descriptor.getReadMethod() != null) {
Object actualParent = ReflectionUtils.invokeMethod(descriptor.getReadMethod(), candidate);
if (Objects.equals(parent, actualParent)) {
children.add(candidate);
}
}
}
}
}
return children;
}
/**
* @param search 查询条件
* @param entityClass 实体类型
* @param <T>
*/
public static <T> void convertSearchValueToEntityValue(final Searchable search, final Class<T> entityClass) {
if (search.isConverted()) {
return;
}
Collection<SearchFilter> searchFilters = search.getSearchFilters();
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(entityClass);
beanWrapper.setAutoGrowNestedPaths(true);
beanWrapper.setConversionService(getConversionService());
for (SearchFilter searchFilter : searchFilters) {
convertSearchValueToEntityValue(beanWrapper, searchFilter);
}
}
@Override
protected void handleSuccess(HttpServletRequest request, HttpServletResponse response,
UpgradeInfo upgradeInfo, TyrusUpgradeResponse upgradeResponse) throws IOException, ServletException {
response.setStatus(upgradeResponse.getStatus());
upgradeResponse.getHeaders().forEach((key, value) -> response.addHeader(key, Utils.getHeaderFromList(value)));
AsyncContext asyncContext = request.startAsync();
asyncContext.setTimeout(-1L);
Object nativeRequest = getNativeRequest(request);
BeanWrapper beanWrapper = new BeanWrapperImpl(nativeRequest);
Object httpSocket = beanWrapper.getPropertyValue("connection.connectionHandler.rawConnection");
Object webSocket = webSocketHelper.newInstance(request, httpSocket);
webSocketHelper.upgrade(webSocket, httpSocket, request.getServletContext());
response.flushBuffer();
boolean isProtected = request.getUserPrincipal() != null;
Writer servletWriter = servletWriterHelper.newInstance(webSocket, isProtected);
Connection connection = upgradeInfo.createConnection(servletWriter, noOpCloseListener);
new BeanWrapperImpl(webSocket).setPropertyValue("connection", connection);
new BeanWrapperImpl(servletWriter).setPropertyValue("connection", connection);
webSocketHelper.registerForReadEvent(webSocket);
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
Object fieldValue = beanWrapper.getPropertyValue(field);
Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
if (matched) {
return true;
}
else {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode(field)
.addConstraintViolation();
return false;
}
}
protected AbstractBeanDefinition createBeanDefinition() {
AbstractBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(this.clazz);
if (!CollectionUtils.isEmpty(this.constructorArgs)) {
ConstructorArgumentValues cav = new ConstructorArgumentValues();
for (Object constructorArg : this.constructorArgs) {
cav.addGenericArgumentValue(constructorArg);
}
bd.setConstructorArgumentValues(cav);
}
if (this.parentName != null) {
bd.setParentName(this.parentName);
}
this.definitionWrapper = new BeanWrapperImpl(bd);
return bd;
}
/**
* Overridden to copy property editor registration to the new bean wrapper.
*
* <p>This is necessary because spring only copies over the editors when a new bean wrapper is
* created. The wrapper is then cached and use for subsequent calls. But the get calls could bring in
* new custom editors we need to copy.</p>
*
* {@inheritDoc}
*/
@Override
protected BeanWrapperImpl getBeanWrapperForPropertyPath(String propertyPath) {
BeanWrapperImpl beanWrapper = super.getBeanWrapperForPropertyPath(propertyPath);
PropertyTokenHolder tokens = getPropertyNameTokens(propertyPath);
String canonicalName = tokens.canonicalName;
int pos = PropertyAccessorUtils.getFirstNestedPropertySeparatorIndex(canonicalName);
if (pos != -1) {
canonicalName = canonicalName.substring(0, pos);
}
copyCustomEditorsTo(beanWrapper, canonicalName);
return beanWrapper;
}
/**
* Sets object's field annotated with annotationClass to value only if the condition
* matches.
*
* @param domainObj the object containing the field
* @param annotationClass the annotation to look for
* @param value the value to set
* @param condition the condition that must be satisfied to allow the match
*/
public static void setFieldWithAnnotationConditionally(Object domainObj,
Class<? extends Annotation> annotationClass, Object value,
Condition condition) {
Field field = findFieldWithAnnotation(domainObj, annotationClass);
if (field != null && field.getAnnotation(annotationClass) != null
&& condition.matches(field)) {
try {
PropertyDescriptor descriptor = org.springframework.beans.BeanUtils
.getPropertyDescriptor(domainObj.getClass(), field.getName());
if (descriptor != null) {
BeanWrapper wrapper = new BeanWrapperImpl(domainObj);
wrapper.setPropertyValue(field.getName(), value);
return;
}
else {
ReflectionUtils.setField(field, domainObj, value);
}
return;
}
catch (IllegalArgumentException iae) {
}
}
}
protected AbstractBeanDefinition createBeanDefinition() {
AbstractBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(this.clazz);
if (!CollectionUtils.isEmpty(this.constructorArgs)) {
ConstructorArgumentValues cav = new ConstructorArgumentValues();
for (Object constructorArg : this.constructorArgs) {
cav.addGenericArgumentValue(constructorArg);
}
bd.setConstructorArgumentValues(cav);
}
if (this.parentName != null) {
bd.setParentName(this.parentName);
}
this.definitionWrapper = new BeanWrapperImpl(bd);
return bd;
}
@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());
}
@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 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());
}
@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());
}
/**
* 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);
}
}
@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());
}
@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());
}
@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));
}
@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));
}
@Override
public void registerCustomEditors(PropertyEditorRegistry registry) {
if (!(registry instanceof BeanWrapperImpl)) {
return;
}
BeanWrapperImpl beanWrapper = (BeanWrapperImpl) registry;
Class<?> clazz = null;
try {
clazz = Class.forName(SchedulerFactoryBean, true, registry.getClass().getClassLoader());
} catch (Throwable e) {
LOGGER.info("cannot find class for " + SchedulerFactoryBean, e);
}
if (null == clazz
|| null == beanWrapper.getWrappedClass()
|| !clazz.isAssignableFrom(beanWrapper.getWrappedClass())) {
return;
}
registry.registerCustomEditor(Object.class, "triggers",
new QuartzSchedulerBeanTargetEditor(context));
}
public boolean isValid(Object value, ConstraintValidatorContext context) {
BeanWrapper beanWrapper = new BeanWrapperImpl(value);
Object fieldValue = beanWrapper.getPropertyValue(field);
Object comparingFieldValue = beanWrapper.getPropertyValue(comparingField);
boolean matched = ObjectUtils.nullSafeEquals(fieldValue, comparingFieldValue);
if (matched) {
return true;
}
else {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message)
.addPropertyNode(field)
.addConstraintViolation();
return false;
}
}
@Override
public Object autowire(Class<?> beanClass, int autowireMode, boolean dependencyCheck) throws BeansException {
// Use non-singleton bean definition, to avoid registering bean as dependent bean.
final RootBeanDefinition bd = new RootBeanDefinition(beanClass, autowireMode, dependencyCheck);
bd.setScope(BeanDefinition.SCOPE_PROTOTYPE);
if (bd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR) {
return autowireConstructor(beanClass.getName(), bd, null, null).getWrappedInstance();
}
else {
Object bean;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
bean = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(bd, null, parent),
getAccessControlContext());
}
else {
bean = getInstantiationStrategy().instantiate(bd, null, parent);
}
populateBean(beanClass.getName(), bd, new BeanWrapperImpl(bean));
return bean;
}
}
/**
* Instantiate the given bean using its default constructor.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return a 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((PrivilegedAction<Object>) () ->
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);
}
}
@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();
}
}
@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());
}
@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 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());
}
@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());
}
@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());
}
public static MultiValueMap<String, String> convertBeanForQueryParams(Object target, ConversionService conversionService) {
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(target);
beanWrapper.setConversionService(conversionService);
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap();
for (PropertyDescriptor pd : beanWrapper.getPropertyDescriptors()) {
if (beanWrapper.isWritableProperty(pd.getName())) {
Object pv = beanWrapper.getPropertyValue(pd.getName());
if (pv != null) {
if (pv instanceof Collection) {
if (!CollectionUtils.isEmpty((Collection) pv)) {
for (Object element : (Collection) pv) {
queryParams.set(pd.getName(), convertPropertyValueForString(target, pd, element));
}
}
} else {
queryParams.set(pd.getName(), convertPropertyValueForString(target, pd, pv));
}
}
}
}
return queryParams;
}
/**
* 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);
}
}
@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());
}