java BeanUtils 复制属性:注册 ConvertUtils

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12719645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:57:18  来源:igfitidea点击:

BeanUtils Copy Properties: Registering ConvertUtils

java

提问by JR Galia

I have web application written in Java. Im using BeanUtils.copyPropertiesmethod. If a datefield is null, it throws an error. I solved it by using ConvertUtils.registermethod.

我有用 Java 编写的 Web 应用程序。我使用BeanUtils.copyProperties方法。如果date字段为空,则会引发错误。我是用ConvertUtils.register方法解决的。

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?

它现在可以工作,但是使用ConvertUtils.register. 应该放在哪里?

回答by Yogendra Singh

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

您所做的仅对一种类(日期)类型是正确的。这是通过调用 register 方法对包括 Date 在内的所有支持的类型实现的,ConvertUtilsBean如下所示:

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

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

这里,第一个参数false表示不抛出转换异常。第二个参数true表示,如果有异常,则使用 null 作为默认值。第三个参数-1表示数组类型将默认为 null。如果要使用特定大小的默认数组,请将大小作为第三个参数提及。

Refer more details here (ConvertUtilsBean Javadoc).

请参阅此处的更多详细信息(ConvertUtilsBean Javadoc)

回答by Lluis Martinez

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

一个好地方是 ServletContextListener,你只需要做一次。

ServletContextListener not being invoked

ServletContextListener 未被调用