-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotes.txt
More file actions
196 lines (157 loc) · 10.3 KB
/
notes.txt
File metadata and controls
196 lines (157 loc) · 10.3 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
###############################################################################
############################ LIFECYCLE MAVEN ##################################
###############################################################################
1. validate - validate the project is correct and all necessary information is available
2. compile - compile the source code of the project
3. test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
4. package - take the compiled code and package it in its distributable format, such as a JAR.
5. verify - run any checks on results of integration tests to ensure quality criteria are met
6. install - install the package into the local repository, for use as a dependency in other projects locally
7. deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.
Al ejecutar un comando, también se ejecutarán todas las anteriores a esta.
ejm: install: validate + compile + ... + install
Clean: Limpia lo que se ejecutó anteriormente (Borra el package ~ project compiled ~ *.JAR ~ Target)
###############################################################################
############ SETTER VS CONSTRUCTOR BASED DEPENDENCY INJECTION #################
###############################################################################
1. Constructor: Para dependencias obligatorias
2. Setter: Para dependencias opcionales
> A large number of constructor arguments is considered bad practice (3 args should be max)
> A large number of constructor arguments implies that the class likely has too many
responsibilities and should be refactored to better.
> Setter injection -> optional dependencies that can be assigned reasonable default values within the class.
> Otherwhise, not-null checks must be performed everywhere the code uses the dependency.
###############################################################################
########################## CIRCULAR DEPENDENCIES ##############################
###############################################################################
1. One possible solution is to use setter-based injection for one of the classes rather than
constructor-based injection. Alternatively, you can avoid constructor injection and use setter injection only.
2. In other words, although it is not recommended, you can configure circular dependencies with setter injection.
> a circular dependency between been A and been B will force one of the beans to be injected into
the other prior to being fully initialized itself (this is a classic chicken/egg scenario).
###############################################################################
###################### XML VS ANNOTATION CONFIGURATION ########################
###############################################################################
XML Configuration:
<bean id="game" class="academy.learnprogramming.GameImpl">
<constructor-arg ref="numberGenerator"/>
</bean>
~
Annotation Configuration:
@Component
public class GameImpl implements Game {
@Autowired
private NumberGenerator numberGenerator;
...
}
###############################################################################
########################## CONSTRUCTOR INJECTION ##############################
###############################################################################
En caso los campos(field) a inyectar tengan su candidato como componente,
entonces no es necesario que el constructor sea Autowired, y notaremos
que el constructor se coloreará ya que se detectó la relación.
public ConsoleNumberGuess(Game game, MessageGenerator messageGenerator) {
this.game = game;
this.messageGenerator = messageGenerator;
}
En caso alguno de los campos, que su candidato no sea un componente, entonces
el constructor debe ser Autowired
@Autowired
public GameImpl(NumberGenerator numberGenerator, @GuessCount int guessCount) {
this.guessCount = guessCount;
this.numberGenerator = numberGenerator;
}
@Autowired
public NumberGeneratorImpl(@MaxNumber int maxNumber, @MinNumber int minNumber) {
this.maxNumber = maxNumber;
this.minNumber = minNumber;
}
###############################################################################
############################### ANNOTATIONS ###################################
###############################################################################
@Autowired: This annotation allows Spring to resolve and inject collaborating beans into your bean.
@Component: @Repository, @Service and @Controller are specializations of @Component, for more specific use cases.
@Configuration:
> Indica que la clase será usada como XML Configuration (JAVA Annotation Configuration)
@Import:
> Separamos los beans por tema o funcionalidad, en distintas clases para que sea más claro.
> Y en un archivo de configuración principal importamos los otros archivos de configuración.
@ComponentScan(basePackages = "academy.learn") ~ <context:component-scan base-package="academy.learn"/>
> Indica cuales beans serán escaneados
> Si no tiene un argumento entonces escaneará los que se encuentren en el paquete actual
> Si se especifica el paquete, entonces escaneará ese y los sub paquetes que se encuentren dentro
@Bean: Indica que es un bean, cuyo nombre será el del método, de otro modo un bean se puede asociar a
un elemento que tenga el mismo tipo de dato que dicho bean, de ahí que un campo tenga beans candidatos.
@EventListener:
@Component
public class ConsoleNumberGuess {
@EventListener(ContextRefreshedEvent.class)
public void start() {
log.info("Container ready for use.");
}
}
~
@Component
public class ConsoleNumberGuess implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
log.info("Container ready for use.");
}
}
@Qualifier: Es una anotación que se aplica a un bean, de esta manera el contenedor sabrá que debe
hacer un Autowired automáticamente y no tenemos que depender específicamente del nombre de un bean.
--------------> Annotation-based auto wiring <---------------
El container resuelve los beans viendo los calificadores
-> Es por decirlo así crear nuestra anotación.
-> Luego colocar esta anotación al método(bean) que corresponde y al campo(field), los cuales se corresponden
y de esta forma estarán unidos.
-> Esto evitará que un bean tenga distintos candidatos, ya que conectamos el campo con el bean que le corresponde
@Target({ElementType.FIELD, ElementType.PARAMETER, ...}): Indica donde se puede agregar, e.g en los campos, parametro..
@Retention(RetentionPolicy.RUNTIME): Indica el tiempo que se conservará la anotación,
> RetentionPolicy.RUNTIME: Indica que será retenida por la maquina virtual en tiempo de ejecución.
@PropertySource("classpath:config/game.properties") : Nos permite cargar y usar los valores contenidos en el properties file
> Properties file: Archivo cuyo contenido es clave valor, constantes
@Value("${game.maxNumber:20}") : Inyecta el valor asociado a la clave que se encuentra en el properties file
> clave: game.maxNumber
> 20 : Default Value, en caso de no encontrarse la clave en el propertie file se usará el valor por default
###############################################################################
############################ LOMBOK ANNOTATIONS ###############################
###############################################################################
La anotación irá arriba del campo que queremos que actue.
En caso queramos que actue en todos los campos de la clase se colocará arriba del nombre de la clase.
@Getter: Si a un campo le colocamos con el argumento AccessLevel.NONE entonces no accederemos al getter de ese campo
@Setter
@ToString
@EqualsAndHashCode
@RequiredArgsConstructor: will generate a constructor with required arguments
@Slf4j: will generate a private static final field for SLF4J logger
@Data:
> generates boilerplate code for POJO (Plain Old Java Object)
> It combines @Getter + ... + @RequiredArgsConstructor
> Constructor is not generated if it has been declared already
###############################################################################
############################# PATTERN DESIGNS #################################
###############################################################################
> https://medium.com/@gcralos/patrones-de-diseño-en-java-ec7969f572a3
> Patrones: Se definen como una solución ya probada a un problema en específico
> "Un design pattern o patrón de diseño consiste en un diagrama de objetos que forma
una solución a un problema conocido y frecuente"
###############################################################################
################################ SPRING MVC ###################################
###############################################################################
> Model, View and Controller and it is a design pattern
> Model: Models are responsible for managing the application's data, business logic and business rules
> View: The view is an output representation of information, for example displaying information or reports
to the user either as a web form or as charts
> Controller: The controller is responsible for invoking Models to perform business logic and then updating
the view based on the Models output.
> Tenemos un central Servlet, conocido como DispatcherServlet, que proporciona un algoritmo compartido
para el procesamiento de solicitudes.
Controladores que manejan las solicitudes por lo que este diseño es flexible y permite diferentes
flujos de trabajo en los que el DispatcherServlet espera un WebApplicationContext (contexto de aplicación web),
que es una extensión de un plain ApplicationContext, para su propia configuración.
> DispatcherServlet delega beans especiales para procesar solicitudes y render las respuestas apropiadas.
> Con el WebApplicationContext hay algunos beans que se registran automáticamente
> With Spring MVC we can use different view technologies to render web pages.
For example Groovy Markup, Freemarker, and Thymeleaf.
> Spring MVC also integrates with other web frameworks