There was method setWrappedInstance in org.springframework.beans.BeanWrapper in 2.5.6 and was removed in 3.0.0. As i am in the process of migrating my project from 2.5 to 3.0 I get errors. I investigated and the implementation class org.springframework.beans.BeanWrapperImpl still has the method setWrappedInstance implemented.
below is the piece of code from my project which is causing trouble.
public FieldComparator(String fieldName, Class clazz) {
_fieldName = fieldName;
_bw = new BeanWrapperImpl(clazz);
}
public int compare(Object o1, Object o2) {
if (o1 == null && o2 == null) return 0;
else if (o1 == null) return -1;
else if (o2 == null) return 1;
// otherwise
_bw.setWrappedInstance(o1);
Comparable v1 = (Comparable) _bw.getPropertyValue(_fieldName);
_bw.setWrappedInstance(o2);
Comparable v2 = (Comparable) _bw.getPropertyValue(_fieldName);
return NullsLowComparator.INSTANCE.compare(v1, v2);
}
So would it be ok if I just replace _bw implementation with BeanWrapperImpl. I am in the learning stage and I believe that spring strongly suggests to use interfaces rather than implementation classes itself.
Is this change against standard practices or can I just move on with the simple change?
The
BeanWrapper.setWrappedInstancemethod was marked as deprecated in Spring 2.5, and removed altogether in 3.0. Unlike deprecations in the JRE (which never get removed), deprecated APIs in Spring do get removed, so you’re well advised to avoid them.The 2.5.6 Javadoc for
setWrappedInstancesays:In other words, instead of reusing instances of
BeanWrapper, you should create newBeanWrapperImplinstances as required. There’s no performance penalty for this – theBeanWrapperImpljavadoc says that it “Caches introspection results for efficiency.”So replace this:
with this:
and get rid of the
_bwfield altogether.As a general rule of thumb, yes. However, try to apply some practicality to this. Your use of
BeanWrapperImplis restricted entirely to internal implementation detail of your comparator, so there’s no real harm in using it directly. If your comparator were to expose theBeanWrapperin a public method signature, for some reason, then that would be best done using the interface rather than the implementation.