forked from mapstruct/mapstruct
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathObjectFactory.java
More file actions
60 lines (57 loc) · 2.45 KB
/
ObjectFactory.java
File metadata and controls
60 lines (57 loc) · 2.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/*
* Copyright MapStruct Authors.
*
* Licensed under the Apache License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package org.mapstruct;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* This annotation marks a method as a <em>factory method</em> to create beans.
* <p>
* 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.
* <p>
* Factory methods can be defined without parameters, with an {@code @}{@link TargetType} parameter, a
* {@code @}{@link 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.
* <p>
* <strong>Note:</strong> the usage of this annotation is <em>optional</em> when used in the {@link Mapper#uses()}
* if no source parameters are part of the signature, i.e. it is declared without parameters or only with
* {@code @}{@link TargetType} and/or {@code @}{@link Context}. It is however <em>mandatory</em> when used inside
* an {@code @}{@link Context} annotated class.
* <p>
* <strong>Example:</strong> Using a factory method for entities to check whether the entity already exists in the
* EntityManager and then returns the managed instance:
*
* <pre>
* <code>
* @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();
* }
* }
* </code>
* </pre>
* <p>
* 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.
*
* @author Remo Meier
* @since 1.2
*/
@Retention(RetentionPolicy.CLASS)
@Target(ElementType.METHOD)
public @interface ObjectFactory {
}