Difference between revisions of "Spring 5 training (Spring guru) - personal notes"
(→Spring beans lifecycle) |
(→IntelliJ configuration) |
||
(22 intermediate revisions by the same user not shown) | |||
Line 7: | Line 7: | ||
* [http://start.spring.io Spring initializr] - to generate a quick start project based on the libraries you choose | * [http://start.spring.io Spring initializr] - to generate a quick start project based on the libraries you choose | ||
+ | * [https://start.jhipster.tech/jdl-studio/ JHipster JDL Studio] - to generate UML online *** AMAZING *** | ||
+ | * [https://www.jhipster.tech/ JHipster] - to quick start projects | ||
+ | |||
+ | |||
+ | =Tools= | ||
+ | |||
+ | To develop you need: | ||
+ | * [https://www.mozilla.org/en/firefox/developer/ Firefox developer edition] | ||
+ | * [https://www.jetbrains.com/idea/ Intellij] or [https://www.eclipse.org/ Eclipse IDE] | ||
+ | * [http://livereload.com/ LiveRelaod browser plugin] to work with Spring Boot developer tools | ||
Line 20: | Line 30: | ||
− | =H2 | + | =GIT= |
+ | |||
+ | Some tricks about GIT and GitHub. | ||
+ | * How to fork a repo and keep it updated? https://help.github.com/articles/fork-a-repo/ | ||
+ | * How to sync a fork? https://help.github.com/articles/syncing-a-fork/ | ||
+ | |||
+ | |||
+ | =Database= | ||
+ | |||
+ | ==H2== | ||
When using H2 on a web application, don't forget to enable the console! Edit <code>application.properties</code> as follow: | When using H2 on a web application, don't forget to enable the console! Edit <code>application.properties</code> as follow: | ||
Line 33: | Line 52: | ||
− | =Hibernate= | + | ==Hibernate== |
− | ==General notes== | + | ===General notes=== |
Hibernate recommends to implement <code>hashCode()</code> and <code>equals()</code> on all JPA entities. They also recommend to use a particular ''Business ID'' when possible, if not then use the ''ID''. Only the key fields should be in these methods. | Hibernate recommends to implement <code>hashCode()</code> and <code>equals()</code> on all JPA entities. They also recommend to use a particular ''Business ID'' when possible, if not then use the ''ID''. Only the key fields should be in these methods. | ||
+ | |||
+ | |||
+ | ===Initial dataset=== | ||
+ | |||
+ | You can use HIBERNATE to load an initial dataset [<code>import.sql</code>] ONLY if the DDL-AUTO property is set to ''create'' or ''create-drop''. | ||
+ | |||
+ | IMPORTANT: '''!! You must NOT use Hibernate 'import.sql' with Spring JDBC generators 'data.sql' or 'schema*.sql'. It is either HIBERNATE or SPRING, not both !!''' | ||
+ | [[File:Hibernate databaset initialization.png|1024px|caption|Hibernate database's dataset initialization, Copyright: Spring Guru (John Tompson)]] | ||
+ | |||
+ | |||
+ | ==Spring JDBC== | ||
+ | |||
+ | Spring boot can initialize data through Spring JDBC by loading | ||
+ | |||
+ | IMPORTANT: '''!! You must NOT use Hibernate 'import.sql' with Spring JDBC generators 'data.sql' or 'schema*.sql'. It is either HIBERNATE or SPRING, not both !!''' | ||
+ | |||
+ | [[File:Spring-boot-dataset-initialization.png|1024px|caption|Hibernate database's dataset initialization, Copyright: Spring Guru (John Tompson)]] | ||
+ | |||
+ | |||
+ | |||
+ | =JPA= | ||
+ | |||
+ | Some notes related to JPA | ||
+ | |||
+ | ==Fetch types== | ||
+ | |||
+ | Since JPA 2.1 some operations are EAGER and others are LAZY: | ||
+ | |||
+ | [[File:Jpa fetch type.png|1024px|caption|JPA fetch type (credentials: Spring Guru, UDEMY)]] | ||
+ | |||
+ | |||
+ | ==Cascade== | ||
+ | |||
+ | Here are some cascading features (by '''default: nothing is cascade!'''): | ||
+ | |||
+ | |||
+ | [[File:JPA 2.1 cascade page1.png|1024px|caption|JPA cascade page 1 (credentials: Spring Guru, UDEMY)]] | ||
+ | |||
+ | |||
+ | [[File:JPA 2.1 cascade page2.png|1024px|caption|JPA cascade page 2 (credentials: Spring Guru, UDEMY)]] | ||
+ | |||
+ | |||
+ | ==Timestamps== | ||
+ | |||
+ | It is considered a good practice to keep track of creation and update time-stamps: | ||
+ | |||
+ | [[File:JPA 2.1 timestamps.png|1024px|caption|JPA timestamps (credentials: Spring Guru, UDEMY)]] | ||
Line 43: | Line 109: | ||
=IntelliJ configuration= | =IntelliJ configuration= | ||
+ | |||
+ | |||
==Plugins== | ==Plugins== | ||
Line 53: | Line 121: | ||
** Save actions | ** Save actions | ||
** GenerateSerialVersion | ** GenerateSerialVersion | ||
+ | ** Axis TCP monitor | ||
Enable toolbars! View > Toolbar | Enable toolbars! View > Toolbar | ||
Line 65: | Line 134: | ||
* '''Settings''' | Editor | General | Auto Import > Optimize imports on the fly | * '''Settings''' | Editor | General | Auto Import > Optimize imports on the fly | ||
* '''Commit Project dialog''' > Optimize imports option | * '''Commit Project dialog''' > Optimize imports option | ||
+ | |||
+ | |||
+ | ==Save actions== | ||
+ | |||
+ | See this very good [https://stackoverflow.com/questions/946993/intellij-reformat-on-file-save thread on StackOverflow] | ||
+ | |||
+ | |||
+ | ==Generate SerialVersionUID== | ||
+ | |||
+ | Enable: <code>File => Settings => Editor => Inspections => Serialization issues => Serializable class without 'serialVersionUID' enabled</code> | ||
+ | |||
+ | Then you will have warnings and you'll be able to generate the SerialVersionUID. | ||
+ | |||
+ | |||
+ | source [https://stackoverflow.com/questions/12912287/intellij-idea-generating-serialversionuid StackOverflow] | ||
+ | |||
+ | |||
+ | ==Compile on save== | ||
+ | |||
+ | ===Registry tweak=== | ||
+ | |||
+ | You can configure IntelliJ to behave like Eclipse: automatically rebuild the project and deploy it on save. | ||
+ | |||
+ | Open the Registry: | ||
+ | * '''Ctrl + Shift + A''' (windows, Linux) || Command + Shift + A (apple) | ||
+ | * Type "'''Registry'''" | ||
+ | * Search for the key '''compiler.automake.allow.when.app.running''' to enable the feature. Description of that key: <code>Allow auto-make to start even if developed application is currently running. Note that automatically started make may eventually delete some classes that are required by the application.</code> | ||
+ | |||
+ | That's it! You can close the registry. | ||
+ | |||
+ | |||
+ | ===Enable auto-build=== | ||
+ | |||
+ | You have to enable the ''auto-build'': | ||
+ | * File > Settings > Build, Execution, Deployment > Compiler | ||
+ | * Enable "'''Build project automatically'''" | ||
Line 82: | Line 187: | ||
On the main menu, choose File | New | Project | On the main menu, choose File | New | Project | ||
* Left side: Spring initalizr (IntelliJ ultimate) | * Left side: Spring initalizr (IntelliJ ultimate) | ||
+ | |||
+ | =HTTP protocol= | ||
+ | |||
+ | Just some quick summary related to HTTP protocol and HTTP requests: | ||
+ | |||
+ | [[File:Http requests summary.png|1024px|caption|HTTP requests summary (credentials: Spring Guru, UDEMY)]] | ||
+ | |||
Line 87: | Line 199: | ||
=Spring 5= | =Spring 5= | ||
− | == | + | ==Spring properties== |
+ | |||
+ | You can find the '''properties hierarchy''' over here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html | ||
+ | |||
+ | |||
+ | ==command line tricks== | ||
Spring boot provides some out-of-the-box tools. | Spring boot provides some out-of-the-box tools. | ||
+ | |||
+ | |||
+ | ===Run the application=== | ||
To run the application: | To run the application: | ||
Line 100: | Line 220: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | |||
+ | ===See spring-boot commands=== | ||
+ | |||
+ | <syntaxhighlight lang="bash"> | ||
+ | mvn spring-boot:help -Ddetail=true | ||
+ | </syntaxhighlight> | ||
+ | |||
+ | |||
+ | ===See all spring boot magic=== | ||
+ | |||
+ | To see all the magic you can start in FULL DEBUG mode. This is more than the "DEBUG" logs! | ||
+ | This will: | ||
+ | * Load the application | ||
+ | * Display each spring action such as component scan, auto-configuration, properties load, ignore beans and configuration | ||
+ | * Give additional information regarding spring beans access and catalog update | ||
+ | * etc. | ||
+ | |||
+ | <syntaxhighlight lang="bash"> | ||
+ | mvn spring-boot:run -Dspring-boot.run.arguments=--debug | ||
+ | </syntaxhighlight> | ||
==Spring MVC== | ==Spring MVC== | ||
Line 128: | Line 268: | ||
==Spring beans lifecycle== | ==Spring beans lifecycle== | ||
− | This section describes Spring's beans lifecycle. It is an extract of [https://www.udemy.com/spring-framework-5-beginner-to-guru Spring 5 training] from John Tompson | + | This section describes Spring's beans lifecycle. It is an extract of [https://www.udemy.com/spring-framework-5-beginner-to-guru Spring 5 training] from John Tompson. This is a summary of lecture 37. |
+ | |||
===Creation=== | ===Creation=== | ||
Line 162: | Line 303: | ||
# Bean ready to use | # Bean ready to use | ||
# '''Post processing''' by executing the <code>@PostConstruct</code> | # '''Post processing''' by executing the <code>@PostConstruct</code> | ||
+ | |||
+ | |||
+ | |||
+ | ===Awareness=== | ||
+ | |||
+ | In the 'initialization' phase - as well as the 'reload' phase - you might want to '''listen to events''' that occurs within the application and have impact on the Spring context. | ||
+ | Here is a list of the most common ''aware'' interfaces: | ||
+ | |||
+ | [[File:Spring bean creation aware interfaces.png|1024px|caption|Spring aware interfaces (credentials: Spring Guru, UDEMY)]] | ||
+ | |||
+ | |||
+ | In all honesty, I've only worked with the <code>ApplicationContextAware</code> interface in 7 years of Spring. | ||
+ | |||
+ | |||
+ | |||
Line 173: | Line 329: | ||
# '''Disposable''' phase: Spring will call the ''@PreDestroy'' method | # '''Disposable''' phase: Spring will call the ''@PreDestroy'' method | ||
# You can also specify a '''custom destroy''' method that will be call at the end by implementing <code>DisposableBean.destroy()</code>. This is useful for custom socket connections close (example). Ideally, on new applications you should NOT use that custom part at all. | # You can also specify a '''custom destroy''' method that will be call at the end by implementing <code>DisposableBean.destroy()</code>. This is useful for custom socket connections close (example). Ideally, on new applications you should NOT use that custom part at all. | ||
+ | |||
+ | |||
+ | ==Spring bean components== | ||
+ | |||
+ | ===Hierarchy=== | ||
+ | |||
+ | You'll find below the Spring beans components hierarchy: | ||
+ | |||
+ | [[File:Spring bean hierarchy.png|1024px|caption|spring beans hierarchy (credentials: Spring Guru, UDEMY)]] | ||
+ | |||
+ | Each type @Controller, @Service, @Repository provides additional @nnotations + they are marked to belong to a particular N-third layer. This helps Spring a lot. | ||
+ | |||
+ | ===Beans types=== | ||
+ | |||
+ | [[File: Spring beans types.png|1024px|caption|spring beans types (credentials: Spring Guru, UDEMY)]] |
Latest revision as of 17:13, 11 April 2018
I recently (2018) subscribe to an online training related to Spring 5 on Udemy. This page is a sum-up of my personal notes related to Spring 5.
Contents
Links
- Spring initializr - to generate a quick start project based on the libraries you choose
- JHipster JDL Studio - to generate UML online *** AMAZING ***
- JHipster - to quick start projects
Tools
To develop you need:
- Firefox developer edition
- Intellij or Eclipse IDE
- LiveRelaod browser plugin to work with Spring Boot developer tools
Very simple web-application
- Go to Spring initializr
- Select
- web > web
- SQL > JPA
- SQL > H2
- Templates > Thymeleaf
- Ops > actuator
GIT
Some tricks about GIT and GitHub.
- How to fork a repo and keep it updated? https://help.github.com/articles/fork-a-repo/
- How to sync a fork? https://help.github.com/articles/syncing-a-fork/
Database
H2
When using H2 on a web application, don't forget to enable the console! Edit application.properties
as follow:
spring.h2.console.enabled=true
# replace "spring5webapp" by your own application
spring.datasource.url=jdbc:h2:mem:spring5webapp;DB_CLOSE_ON_EXIT=FALSE
Then you can reach the console at http://localhost:8080/h2-console
Hibernate
General notes
Hibernate recommends to implement hashCode()
and equals()
on all JPA entities. They also recommend to use a particular Business ID when possible, if not then use the ID. Only the key fields should be in these methods.
Initial dataset
You can use HIBERNATE to load an initial dataset [import.sql
] ONLY if the DDL-AUTO property is set to create or create-drop.
IMPORTANT: !! You must NOT use Hibernate 'import.sql' with Spring JDBC generators 'data.sql' or 'schema*.sql'. It is either HIBERNATE or SPRING, not both !!
Spring JDBC
Spring boot can initialize data through Spring JDBC by loading
IMPORTANT: !! You must NOT use Hibernate 'import.sql' with Spring JDBC generators 'data.sql' or 'schema*.sql'. It is either HIBERNATE or SPRING, not both !!
JPA
Some notes related to JPA
Fetch types
Since JPA 2.1 some operations are EAGER and others are LAZY:
Cascade
Here are some cascading features (by default: nothing is cascade!):
Timestamps
It is considered a good practice to keep track of creation and update time-stamps:
IntelliJ configuration
Plugins
Useful plugings:
- File > Settings > Plugins > Browse repositories
- .ignore
- Ideolog
- Sonarlint
- Save actions
- GenerateSerialVersion
- Axis TCP monitor
Enable toolbars! View > Toolbar
Import optimization
IntelliJ IDEA offers 2 options:
- Settings | Editor | General | Auto Import > Optimize imports on the fly
- Commit Project dialog > Optimize imports option
Save actions
See this very good thread on StackOverflow
Generate SerialVersionUID
Enable: File => Settings => Editor => Inspections => Serialization issues => Serializable class without 'serialVersionUID' enabled
Then you will have warnings and you'll be able to generate the SerialVersionUID.
source StackOverflow
Compile on save
Registry tweak
You can configure IntelliJ to behave like Eclipse: automatically rebuild the project and deploy it on save.
Open the Registry:
- Ctrl + Shift + A (windows, Linux) || Command + Shift + A (apple)
- Type "Registry"
- Search for the key compiler.automake.allow.when.app.running to enable the feature. Description of that key:
Allow auto-make to start even if developed application is currently running. Note that automatically started make may eventually delete some classes that are required by the application.
That's it! You can close the registry.
Enable auto-build
You have to enable the auto-build:
- File > Settings > Build, Execution, Deployment > Compiler
- Enable "Build project automatically"
Outline like Eclipse (structure view)
see https://www.jetbrains.com/help/idea/viewing-structure-of-a-source-file.html
To view the file structure, do one of the following
- On the main menu, choose View | Tool Windows | Structure.
- Pres StructureTool Button
- Press Alt+7.
- Press Ctrl+F12.
Create new Spring project
On the main menu, choose File | New | Project
- Left side: Spring initalizr (IntelliJ ultimate)
HTTP protocol
Just some quick summary related to HTTP protocol and HTTP requests:
Spring 5
Spring properties
You can find the properties hierarchy over here: https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html
command line tricks
Spring boot provides some out-of-the-box tools.
Run the application
To run the application:
# Using the maven installation (outside the project)
mvn spring-boot:run
# Using the embedded tool
./mvnw spring-boot:run
See spring-boot commands
mvn spring-boot:help -Ddetail=true
See all spring boot magic
To see all the magic you can start in FULL DEBUG mode. This is more than the "DEBUG" logs! This will:
- Load the application
- Display each spring action such as component scan, auto-configuration, properties load, ignore beans and configuration
- Give additional information regarding spring beans access and catalog update
- etc.
mvn spring-boot:run -Dspring-boot.run.arguments=--debug
Spring MVC
Implementation of MVC concept in Spring:
Here is a short description of the schema - as I understood it + based on my experience with Spring so far (v2 to v4):
- Client submits a request to the server (HTTP request)
- Dispatcher receives the request
- Dispatcher asks the Handler WHO should take care of the request? i.e:
- What is the Controller for the requested endpoint?
- Is there any java Method that match the given HTTP request type (GET, POST, PUT, ..) + arguments?
- Dispatcher invokes the Controller and forwards query
- Controller calls a Service to process the query, interact with the database and other systems.
- Once the Service processing is complete, it returns corresponding data to the Controller
- The Controller will convert the data into a DTO (communication Model (pojo)
- Controller sends the pojo back to the Dispatcher
- Data disposal: The Dispatcher disposes of the data. i.e:
- Send back the data directly to the client [HTTP REST calls]
- Forward the data to a View for rending
- View generates the page thanks to UI technology (server side) such as JSP, JSF or Themeleaf to generate HTML / Javascript / CSS
- View sends back generated content to Dispatcher
- Dispatcher forwards content to the Client
Spring beans lifecycle
This section describes Spring's beans lifecycle. It is an extract of Spring 5 training from John Tompson. This is a summary of lecture 37.
Creation
This is how beans are created with Spring:
Complete description
This is the complete description of the creation lifecyle:
- instantiation of the Class. Spring will inject dependencies through the constructor, if available.
- populate properties. Spring will set the @Value attributes: it will perform placeholder resolution against environment, properties files, profiles settings, etc.
- BeanPostProcessing : set of operations that are performed once the bean has been initialized (the Object composition is complete). You just have to implements the
BeanPostProcessort
interface. These features are usually NOT used.- Pre-initialization phase: to customize the bean (and its properties) for some advanced tricks.
- After properties. To get notify once the properties are set. You have to implements
Initializing.afterPropertiesSet()
interface. - You can implement some custom loader.
- Post-initialization phase: to customize the bean once properties are set and custom loader is complete.
- Bean ready to use
There is one extra step that is not on the schema: Post processing. Spring will run the @PostConstruct
method.
Simplify lifecycle
Some steps of the lifecycle are mostly dedicated to the Spring creators and related frameworks.
Most of the Spring users only use:
- instantiation through the Spring bean's constructor
- properties by setting the @Value attributes
- Bean ready to use
- Post processing by executing the
@PostConstruct
Awareness
In the 'initialization' phase - as well as the 'reload' phase - you might want to listen to events that occurs within the application and have impact on the Spring context. Here is a list of the most common aware interfaces:
In all honesty, I've only worked with the ApplicationContextAware
interface in 7 years of Spring.
Destroy
This is how beans are destroyed with Spring:
- Container (Tomcat, Jetty, Bash, etc.) will send the shutdown signal to the application
- Disposable phase: Spring will call the @PreDestroy method
- You can also specify a custom destroy method that will be call at the end by implementing
DisposableBean.destroy()
. This is useful for custom socket connections close (example). Ideally, on new applications you should NOT use that custom part at all.
Spring bean components
Hierarchy
You'll find below the Spring beans components hierarchy:
Each type @Controller, @Service, @Repository provides additional @nnotations + they are marked to belong to a particular N-third layer. This helps Spring a lot.