Please enable JavaScript.
Coggle requires JavaScript to display documents.
Spring / Spring Boot, Metadata (XML, Java code, Annotation) - Coggle…
Spring / Spring Boot
PLATEFORM
Boot vs Spring
Apache server embedded in Spring boot to run the app. Useful for web-service architecture and easy deployment
-
-
-
Spring Initializr (CLI)
Platform where you can initialize your project by choosing dependencies manager, spring module, libraries ...
-
BASIC
Spring framework
-
Why: Based on JEE, Open Source, Loosely coupled and lightweight
Benefits
POJO Based => No need of EJB container, only need a robust servlet container like Tomcat
-
Integration with existing framework => Use of existing frameworks like ORM, logging, JEE framework
-
-
-
-
-
Key words
Dependency Injection (DI) : A way to inject a class A into a class B by using IoC (Inversion Of Control)
Aspect Oriented Programming (AOP) : Decouple cross-cutting concerns from the objects that they affect
Architecture
Core container
Core module => Fundamental features (IOC, DI ...)
-
Context module => Layer under Core and Bean which allows to access any object defined and configured through ApplicationContext interface
-
-
Web (MVC / Remoting)
Web module => basic web-oriented integration features (multipart file-upload, Init of the IOC container using servlet listener and a web-oriented application context )
-
-
-
Miscellaneous
-
-
Instrumentation module => Class instrumentation support and class loader implementations used in certain app servers
-
-
IOC Container
Spring container creates objects (Spring beans), wires them together, configures them and manages their life cycle from creation till destruction
The container gets its instructions on what and how objects to manage by reading the configuration metadata provided through an XML, Java annotations or Java code
-
Spring containers
Spring BeanFactory container => simplest container providing basic support for DI and is defined by BeanFactory interface
Spring ApplicationContext Container => sub layer of BeanFactory container that adds more enterprise-specific functionality such as resolving textual messages from properties file and app event publication to event listener. It's defined by ApplicationContext Interface
Bean's Metadata
-
-
-
-
-
-
-
-
-
<beans>
..<bean id = "..." class = "..." lazy-init = "true">
....<property name="..." value="..." />
....<constructor-arg ref = "..."/>
....<property name="..." ref="..." />
....<property name="...">
........<bean id = "..." class="..." />
....</property>
..</bean>
</beans>
:warning:
- A bean can implement the BeanPostProcessor interface to change the logic of instanciation, configuration, initialization and destruction of beans in IOC container.
- We can make a bean definition inheritance by using the parent property of the bean tag => use the parent bean definition as a template to render the child. No related to inheritance in OOP
- It's possible to create a Bean definition template and call it as a parent for bean definition inheritance. Same like common bean definition with the attribute abstract = "true"
- Autowiring can be used with explicit defination that override it. Autowiring is not very easy to read and maintain so pay attention on.
Dependency Injection
Type
Setter-based DI => Invoked when calling a setter methods on bean in case of no-argument constructor usage (property tag with ref attribut)
Constructor-based DI => Container invokes an argument constructor with dependencies (Contructor-arg tag)
:warning:
- It's possible to use both methods, in case of mandatory dependency injection through the constructor and the setter DI for optional dependency
- You can define an inner bean in the property tag of the bean tag. (See example above)
Collection Injection
List: <property name = "...">
....<list>
........<value>...</value>
........<ref bean="..."/>
....</list>
</property>
Set: <property name = "...">
....<set>
........<value>...</value>
........<ref bean="..."/>
....</set>
</property>
Map: <property name = "...">
....<map>
........<entry key=".." value="..." />
........<entry key=".." value-ref="..." />
....</map>
</property>
Properties: <property name = "...">
....<props>
........<prop key="...">...</prop>
........<prop key="...">...</prop>
....</list>
</property>
Annotation Based Conf.
Not default and enable with the <context:annotation-config/> | @ SpringBootApplication | @ EnableAutoConfiguration
Annotations
@ Required => bean property, setter methods to render the setter-based DI
@ Autowired(required = true) => bean setter methods, non-setter methods, constructor and properties
@ Qualified("identifier") => Used with @ Autowired to specify a bean in case of many bean of the same type
-
-
-
ApplicationContext
During ApplicatioContext livecycle, ApplicationEvents are trowed and listened by beans that implement ApplicationListener interface
-
:warning:
-It's possible to create custom event by creating a child of ApplicationEvent, create a listener of this Event and publishEvent through ApplicationEventPublisher
MODULES
AOP Module
Goal: Separate cross-cutting concerns (functions that span multiple points of an app) to the app's business logic
-
DATA Module
Transaction module
-
Types
Local transactions are specific to a single transactional resource like a JDBC connection, whereas global transactions can span multiple transactional resources like transaction in a distributed system.
Management
-
Declarative transaction management => Separate transaction management from business code by using annotation or XML)based conf
JDBC / ORM module
-
ORM
Concepts
JPA
JPA is a java specification for ORM management. Hibernate, EclipseLink ... are implementations of JPA
-
-
- DAO is an abstraction of data persistence. A repository (JPA) is an abstraction of a collection of objects
- DAO is a lower-level concept, closer to the storage systems. Repository is a higher-level concept, closer to the Domain objects
- Repository is on top of DAO => Repository prepare the data and the DAO stores the datas in DB
Anotation
-
@ Table(name="...", uniqueContraints = @ UniqueContraint... ) => Map a domaine to a table
@ UniqueContraint(name="...", columnNames = "...") => Define an unique constraint
-
@ Column(name="...", nullable= false) => Map an attribut with table column
@ SequenceGenerator(name="...", sequenceName = "...", allocationSize = 1) => Create a sequence
@ GeneratedValue (strategy = ..., generator ="...") => To set a sequence logic
-
-
-
-
-
@ Emberddable / @ Embedded => Define a subclass of a domaine / Specify that a field is an embedded class
-
-
Relations
-
@ JoinColumn (name ="...", referencedColumnName ="...") => To map foreign key in relation
-
@ JoinTable(name="...", joinColumns , inverseJoinColumns) => use to map foreign keys table in N to N relation
MVC WEB
The Spring Web MVC framework is designed around a DispatcherServlet that handles all HTTP requests and responses
Annotations
-
@ RequestMapping("..." | value ="...", method = RequestMethod.POST|GET|PUT) => map url to a class or method
-
-
-
-
-
Exception
-
@ ExceptionHandler(value = ExceptionClassName.class) => Handle a specific class Exception by a method
:warning: Instead of using @ controllerAdvice, you can use a parent controller where you handle each exception
:warning: @ Controller vs @ RestController:
- @ RestController == @ Controller + @ ResponseBody(JSON)
- @ RestController is used for Restfull API and @ Controller is used for MVC app
- @ Controller's methods can return a view instead of JSON as @ RestController
SECURITY
Features
-
Detection and prevention of attacks (session fixation, clickjacking ...)
-
-
-
Authentification
Types
HTTP Authentification
Basic authentification => user/psw in the header of HttpRequest and encoded using base64 (Autorization property)
Digest authentification => same like basic but applies hash function to user/psw/Http method and URI
Forms Authentification
Authentification through a form with a cookie session is created, sent to client and add to all HTTP requests, if authenticated and
-
Token
Json Web Token (JWT) digital signes authenticated requests by a token (Secret key Hashed json data) in the header
-
-
-
Configure
@ Configuration + @ EnableWebSecurity + extends WebSecurityConfigurationAdapter => To add custom security configurations
@ Override configure(HttpSecurity http) => to configure access to request URI and choose authentification type
http
.authorizedRequests()
.antMatchers("/uri").permitAll()
.antMatchers("/uri/**").authentificated()
.antMatchers("/uri").hasRole("ROLE")
.antMatchers("/uri").hasAnyRole("ROLE1", "ROLE2")
.antMatchers("/uri").hasAuthorities("ROLE1", "ROLE2")
.and()
.httpBasic() | .formLogin().loginPage("Url").permitAll()
@ Override configure(AuthentificationManagerBuider auth) => to build a User objects withUser, password, roles, authorities
-
Manage Credential
Build UserDetails
1- create a service that implements UserDetailService to find an User in db by user/psw
2 - Create a class UserPrincipal that implements UserDetails and have a User property to implement interface methods
3- Override Userdetails loadUserByUsername(String s) in the service to find user and return UserDetail
4- Create @ Bean DaoAuthentificationProvider authentificationProvider() in Spring security conf class (DAO for db)
5- Add the AuthentificationProvider to @ Override configuration(AuthentificationManagerBuilder auth) in the config class
Form Authentification
Logout
Add to your HttpSecurity configuration => and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.logoutSuccessUrl("/login")
RemberMe
To create a long time session, you can use remember-me by:
1- Add a checkbox to login form
2- Add a .remberMe() to your HttpSecurity configuration
3- After each authentification a session will be created and the id will be sent to client as cookie with another rememberMe cookie that contains availability period
-
Metadata (XML, Java code, Annotation)
-