Package org.mapstruct

Annotation Type ObjectFactory

  • @Retention(CLASS)
    public @interface ObjectFactory
    This annotation marks a method as a factory method to create beans.

    By default beans are created during the mapping process with the default constructor. If a factory method with a return type that is assignable to the required object type is present, then the factory method is used instead.

    Factory methods can be defined without parameters, with an @TargetType parameter, a @Context parameter, or with the mapping source parameter. If any of those parameters are defined, then the mapping method that is supposed to use the factory method needs to be declared with an assignable result type, assignable context parameter, and/or assignable source types.

    Note: the usage of this annotation is optional when used in the Mapper.uses() if no source parameters are part of the signature, i.e. it is declared without parameters or only with @TargetType and/or @Context. It is however mandatory when used inside an @Context annotated class.

    Example: Using a factory method for entities to check whether the entity already exists in the EntityManager and then returns the managed instance:

     @ApplicationScoped // CDI component model
     public class ReferenceMapper {
         private EntityManager em;
         public <T extends AbstractEntity> T resolve(AbstractDto sourceDto, @TargetType Class<T> type) {
             T entity = em.find( type, sourceDto.getId() );
             return entity != null ? entity : type.newInstance();

    If there are two factory methods, both serving the same type, one with no parameters and one taking sources as input, then the one with the source parameters is favored. If there are multiple such factories, an ambiguity error is shown.

    Remo Meier