【问题标题】:JAXB Class Instance ListenerJAXB 类实例侦听器
【发布时间】:2026-01-29 09:00:02
【问题描述】:

指定基于类实例的 JAXB 侦听器(如在实体 Bean 中)的方法是:afterUnmarshall , beforeMarshall 但基于每个类实例(通过实现任何接口或通过注释)。

@XmlRootElement(name = "Person")                            // Edited
    public class Person {
        protected String name; //setter getter also implemented

        void beforeMarshall(){
         //..........
        }

        void afterUnmarshall (){  // by implementing any interface or by annotation
         //..........
        }
 } 

【问题讨论】:

    标签: java xml-parsing jaxb jaxb2


    【解决方案1】:

    JAXB 将为这些事件匹配以下方法签名:

       // This method is called immediately after the object is created and before the unmarshalling of this 
       // object begins. The callback provides an opportunity to initialize JavaBean properties prior to unmarshalling.
       void beforeUnmarshal(Unmarshaller, Object parent);
    
       //This method is called after all the properties (except IDREF) are unmarshalled for this object, 
       //but before this object is set to the parent object.
       void afterUnmarshal(Unmarshaller, Object parent);
    

    【讨论】:

    • 是否需要实现接口或只指定这些方法签名?
    • 谢谢@Blaise,工作正常。不需要实现接口或注解。
    • @userG - 无需实现任何接口,只需方法签名即可。 JAXB 中没有与 JPA 事件注释等效的功能。
    • 是否也存在 beforeMarshall() & afterMarshall() 方法,(我已经应用了这两个 marshall Listener 但不起作用)。