推土机映射中的常量
有谁知道如何使用推土机将常量值放入属性中? 我在推土机的文档中没有看到任何相关内容
does anybody know how to put a constant value into an attribute with dozer? I haven't seen anything about that in the dozer's documentation
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
不完全确定你的意思 - 如果你希望 Dozer 在从 BeanA 映射到 BeanB 时总是用常量填充 BeanB.someField ?
您可能需要为此映射注册一个自定义转换器。
Not entirely sure what you mean - if you want Dozer to always populate BeanB.someField with a constant whenever you map from BeanA to BeanB?
You might want to register a custom converter for this mapping.
如何利用事件机制?
因此,您可以注册一个侦听器,该侦听器将在侦听器的
mappingFinished()
中设置值。有关详细信息,请参阅有关事件的推土机文档。 当然,您必须使用某种
if ... instanceof
条件来保护设置代码。How about taking advantage of the events mechanism?
So you could register a listener which would do the setting of the value in
mappingFinished()
of your listener.Consult dozer doc on events for details. Of course you would have to guard the setting code with some kind of
if ... instanceof
condition.最近构建的推土机使这变得更容易。 您可以指定自定义转换器并且您可以为给定字段映射指定该转换器的参数。 创建一个单一的“ConstantConverter”应该很简单,它会接受一个输入参数并在 100% 的情况下将其放入输出字段。
Recent builds of dozer make this easier. You can specify both custom converters and you can specify parameters to that converter for a given field mapping. It should be trivial to create a single 'ConstantConverter' that will take an input parameter and put that in the output field 100% of the time.
一种可能的实现是:
示例:
此自定义转换器假定 b-class-fieldname 的类型为 String。
One possible implementation is:
Example:
This Custom Convertor is assumes that the b-class-fieldname is of type String.
假设您只想在单向映射中执行此操作,则以下内容适用于字符串常量:
...调用者:
建议使用
class
值作为虚拟“源字段”,因为尚未使用getClass()
方法保证存在于任何对象上。我需要为布尔值执行此操作,所以使用了这个:
Assuming you only want to do this in a one-way mapping, the following will work for a String constant:
... invoked by:
Would recommend using the
class
value as a dummy "source field" since it is not used yetgetClass()
method is guaranteed to exist on any object.I needed to do it for a Boolean instead so used this: