4

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

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

It works now, but what is the correct way of using ConvertUtils.register. Where should it be placed?

JR Galia
  • 17,229
  • 19
  • 92
  • 144

3 Answers3

6

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

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

Here, first argument false means don't throw conversion exception. Second argument true represents, if there is exception, use null as default value. Third argument -1 represent that array types will be defaulted to null. If you want to default arrays with specific size, mention the size as third parameter.

Refer more details here (ConvertUtilsBean Javadoc).

tuckerpm
  • 191
  • 1
  • 1
  • 10
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
  • every request, this should be called? – JR Galia Oct 04 '12 at 04:23
  • When you call `register` method in your example, `ConvertUtilsBean.getInstance()` `.register(converter, clazz);` code is executed. Since ConvertUtilsBean is retrieved as static reference (pseudo singleton), calling `register` only once per class loader thread should be sufficient. – Yogendra Singh Oct 04 '12 at 04:38
  • you have suggestion to prevent calling it many times in a web application? – JR Galia Oct 04 '12 at 04:38
  • This is what it says. "This is a pseudo-singleton - an single instance is provided per (thread) context classloader. This mechanism provides isolation for web apps deployed in the same container." If your web app is running on single server, only one call should be fine. – Yogendra Singh Oct 04 '12 at 04:41
  • yes, I understand the statement. Im confused where to call the method. Currently, it's on every request. – JR Galia Oct 04 '12 at 04:47
  • As I said, if you are running you app on single server, call it only once. If you are using clustered servers, makes sure, it's called once on each member server of the cluster. – Yogendra Singh Oct 04 '12 at 04:51
  • This is a hilarious conversation. Yogendra, JR is repeatedly asking you HOW to make sure it's only called once, and you keep replying by telling him to make sure it's only called once! – Rob Grant Sep 26 '13 at 11:07
1

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

ServletContextListener not being invoked

Community
  • 1
  • 1
Lluis Martinez
  • 1,963
  • 8
  • 28
  • 42