BeanUtils Copy Properties: Register ConvertUtils

I have a web application written in Java. Im uses the BeanUtils.copyProperties method. If the date field is null, it causes an error. I solved it using the ConvertUtils.register method.

 ConvertUtils.register(new DateConverter(null), Date.class); 

Now it works, but what is the correct way to use ConvertUtils.register . Where should it be located?

+4
source share
3 answers

What you did is CORRECT for only one class (Date). This is achieved for all supported types, including Date, by calling the register method on ConvertUtilsBean , as shown below:

  ConvertUtilsBean convertUtilsBean = BeanUtilsBean.getInstance().getConvertUtils(); convertUtilsBean.register(false, true, -1); 

Here, the first argument false means that it does not throw a conversion exception. The second argument true represents, if there is an exception, uses null as the default value. The third argument -1 means that the array types will default to null. If you want arrays with a specific size by default, specify the size as the third parameter.

See here (ConvertUtilsBean Javadoc) for more details.

+4
source

A good place is ServletContextListener, you just need to do it once.

ServletContextListener is not called

+1
source

Source: https://habr.com/ru/post/1437721/


All Articles