@Retention(value=CLASS) @Target(value=METHOD) public @interface ObjectFactory
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 if no source parameters are part of the
signature, i.e. it is declared without parameters or only with @
TargetType
and/or @
Context
.
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 {
@PersistenceContext
private EntityManager em;
@ObjectFactory
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.
Copyright © 2012-2017 Gunnar Morling; All rights reserved. Released under the Apache Software License 2.0.