Sophie
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Spring formation ## Authors @Sophie @Benjamin @Simon ## Plan ![](https://i.imgur.com/SUykt4e.png) ## Intro - Naissance octobre 2002 - Spring 6.0 en fin d’année 2022 - Patterns d’architecture prédéfinis - Conteneur = cycle de vie, Conteneur IoC : léger, évolutif, maintenable, orienté aspect - Pivotal développe tout - Projet open source - Sous licence Apache 2. - IoC = Inversion of Control = Spring manage le cycle de vie des différent services (injection de dépendances) --- ## DI - Principe : injecter un objet dans un autre - Application Context représente le conteneur Spring, démarre les beans, leurs injections, leur gestions et destructions - Avant: Configuration par XML - Mtn: Annotations, On doit configurer le fait que l’on veut utiliser les annotations ### Setter injection - Convention JavaBeen - Plus clair que constructeur - Dépendances optionnelles ### Constructor injection - Recommandé - Automatique sur dernière version de Spring (plus besoin d'annotation) - Possibilité de rendre objets immutables grâce à "final" - Facile les tests/mock - Oblige à avoir dépendances correctement définies ### Field injection - Spring injecte directement dans le champ grâce à la Java reflexion - Magique - Gênante pour tests unitaires - Plus concise ### Notes - Etre cohérent dans ses types d'injection. - Meilleure portabilité de `@Inject` par rapport à `@Autowired` de Spring. - Bean dispo ou pas: `Optional<Service>` - On peut injecter dynamiquement: `@Value("#toto.getValue()")` --- ## Profiles :warning: Not Program arguments ! :arrow_right: Environment variables : `SPRING_PROFILES_ACTIVE=dev` ```java= context.getEnvironment().setDefaultProfiles("prod"); ``` ```java= @Profile("dev") ``` ## AOP - Joint point = Method Where you want to apply an aspect (poit.proceed) - Point cut = Select several joint points (~regex), ex: - Every methods which are called find...: `(execution(* ...*find*(..)))` - `@Around("execution(* fr.ippon.training.spring.service.*.*(..))")` - Advice = Method to add at the point cut - Aspect = Point + Advice ### Types of aspects - Before advice: before join point - After returning: after joint point - After throwing advice: - After advice: - Around advice (most powerful, wrap of method), ex: ```java @Around("execution(* fr.ippon.training.spring.service.*.*(..))") public Object watchTime(ProceedingJoinPoint point) throws Throwable { Object res; StopWatch stopWatch = new StopWatch(); stopWatch.start(); res = point.proceed(); stopWatch.stop(); log.info("{} temps d'exécution :{}ms", point.getSignature(), stopWatch.getTotalTimeMillis()); return res; } ``` `@Aspect` Annotate class configuration with `@EnableAspectJAutoProxy` ## JDBC `@EnableTransactionManagement` - + basique qu'Hibernate - Setup: ```java @Configuration @ComponentScan("fr.ippon.training.spring") public class ApplicationConfiguration { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) .addScript("classpath:database_init.sql") .build(); } @Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); } } ``` Along with: ```sql= create table Todo (todoId varchar(255) generated by default as identity, description varchar(255), priority integer not null, todoList_listId varchar(255), primary key (todoId)) create table TodoList (listId varchar(255) generated by default as identity, description varchar(255), primary key (listId)) create table User (email varchar(255) not null, password varchar(255), firstName varchar(255), lastName varchar(255), primary key (email)) create table User_TodoList (users_email varchar(255) not null, todoLists_listId varchar(255) not null, primary key (users_email, todoLists_listId)) alter table Todo add constraint FK_todoList_listId foreign key (todoList_listId) references TodoList alter table User_TodoList add constraint FK_users_email foreign key (users_email) references User alter table User_TodoList add constraint FK_todoLists_listId foreign key (todoLists_listId) references TodoList insert into User (email, password, firstName, lastName) values ('philip@ippon.fr', 'Pa$$word1', 'Philip', 'Fry') insert into User (email, password, firstName, lastName) values ('leela@ippon.fr', 'Pa$$word1', 'Leela', 'Turanga') insert into User (email, password, firstName, lastName) values ('bender@ippon.fr', 'Pa$$word1', 'Bender', 'Rodríguez') insert into User (email, password, firstName, lastName) values ('hubert@ippon.fr', 'Pa$$word1', 'Hubert', 'Farnsworth') ``` Use in the code: :warning: Never use concatenation --> Prefer "**prepare statement**" - secu pour les injections SQL - perf ```java= Collection<TodoList> todoLists = jdbcTemplate.query( sql, (rs, i) -> { TodoList todoList = new TodoList(); todoList.setListId(rs.getString("listId")); todoList.setDescription(rs.getString("description")); return todoList; }, listId ); ``` ```java= jdbcTemplate.update("insert into TodoList(listId, description) values (?, ?)", todoList.getListId(), todoList.getDescription()); ``` ## Tests mocks >> stubs (+ maintenable, + easier to setup) ### Mock - Annotate test class with `@ExtendWith(MockitoExtension.class)` - `@InjectMocks`: Entity in which you inject a mock dependency (declared as `@Mock`) - To simulate the return of a mock object: ```java= when(mockUserRepository.getUserByEmail("philip@ippon.fr")).thenReturn(testUser); ``` - To check how many times a method is called ```java verify(mockUserRepository, times(3)).getUserByEmail("philip@ippon.fr"); verify(mockTodoListRepository).createTodoList(todoList); verify(mockTodoListRepository).shareList(todoList, testUser); ``` ```java verifyNoMoreInteractions(mockUserRepository, mockTodoListRepository); ``` ### Stub and field injection When implementing a stub (example userRepositoryStub) which is to be inject by FIELD (example into userService), we must use reflexion :arrow_right: userService depends on userRepositoryStub) ```java= UserRepository userRepository = new UserRepositoryStub(); // Implement roughly the stub. // TODO: Initialize userRepository stub with what you want. UserService userService = new UserServiceImpl(); // Inject stub using java reflexion. ReflectionTestUtils.setField(userService, "userRepository", userRepository); ``` ### Integration Test Annotate test class with ```java= @ExtendWith(SpringExtension.class) // Contexte Spring, allows DI ! @ContextConfiguration(classes = { ApplicationConfiguration.class }) ``` Annotate a test method with `@Transactional` to make it independent between them. (allows to clean the data between 2 tests so that the tests are coherent) ```java= @Test @Transactional ``` ### ORM - ORM tools like Hibernate implements JPA specifications (Java Persistence API). - Allows to focus on the java objects, and business logic. Two main ORMs: - Hibernate (widely used, recommends using the JPA) - EclipseLink **NB**: Search for Spring Data JPA ! (layer on Hibernate) (2012) https://spring.io/projects/spring-data-jpa #### Hibernate ![](https://i.imgur.com/U92nh3m.png) ![](https://i.imgur.com/rIC2SCv.png) **NB**: En fait Hibernate = Room mais pour Android... :see_no_evil: Doc: https://javabydeveloper.com/jpa-entity-lifecycle-jpa-developer-should-know/ Autres API: - JPQL (Java Persistence Query Language) custom request - API Criteria: + complexe, pour des recherches par filtre **NB**: Quarkus --> notion de `ActiveRecord` = une entité peut contenir des *opérations* --> vient de Ruby on Rails Template: permet de faciliter l'utilisation d'Hibernate To make queries into a class, - Add a bean entityManager in the class configuration - Add the property`@PersistenceContext private EntityManager em;` into the classes you want to use. Methods: - Get `em.find(TodoList.class, listId);` - Create `em.persist(todoList);` - Custom query ```java return em.createQuery( "select t from Todo as t join t.todoList tl join tl.users u where u.email = :email", Todo.class) .setParameter("email", email) .getResultList(); ``` :warning: Using @Data for JPA entities is not recommended. It can cause severe performance and memory consumption issues ## Validators - Size of a String `@Size(min = 1, max = 255)` - `@Empty` / `@NotEmpty` - `@AssertTrue` / `@AssertFalse` - `@Null` / `@NotNull` - `@Max` / `@Min` - `@Future` / `@Past` - `@Digits(integer=6, fraction=2)` - `@Pattern(regexp="\\(\\d{3}\\)\\d{3}-\\d{4}")` - ...we can create custom validators ## Spring MVC Spring Web MVC is the original web framework built on the Servlet API and has been included in the Spring Framework from the very beginning. Spring MVC, as many other web frameworks, is designed around the front controller pattern where a central Servlet, the DispatcherServlet, provides a shared algorithm for request processing, while actual work is performed by configurable delegate components. This model is flexible and supports diverse workflows. ### Spring MVC Configuration - Add a web package for your routes and other - :warning: Do not scan the beans defined in this package - Implement the `WebApplicationInitializer` interface - Override `onStartup(ServletContext servletContext)`: - Add a configured listener - `servletContext.addListener(new ContextLoaderListener(rootContext))` - `dispatcherContext.register(WebConfiguration.class);` - Add a Servlet DispatcherServlet - `ServletRegistration.Dynamic servletConfig = servletContext.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));` - `servletConfig.addMapping("/*"); - Add filter to handler ETags - `FilterRegistration.Dynamic etagHeaderFilter = servletContext.addFilter("etagFilter", new ShallowEtagHeaderFilter());` - Add `@EnableWebMvc` in configuration class ### Route configuration To return JSON text : ```java= @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) ``` curl | jq ## Spring Security - Secures REST method calls - Class/File configuration --> XML outdated... again :warning: - **Authentification** = person identity (companies uses LDAP servers) - **Autorization** = correct rights Spring handles both of these concepts Is a user connected? Does he/she have the rights? What error pages? Retrieve person identity: - Spring LDAP - or database (retrieve username then username's roles) ### Config class setup #### HTTP security In the WebConfigurer (startup), add a servlet filter ```java= FilterRegistration.Dynamic delegatingFilterProxy = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy()); delegatingFilterProxy.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC), true, "/*"); ``` - Must implement `WebSecurityConfigurerAdapter` - Annotated with `@EnableWebSecurity` - Override `configure(HttpSecurity http)` method to add http filters (add the filters to http in a functional way) - Override `configure(AuthenticationManagerBuilder auth)` method to add a jdbc manager (authentification) - setup datasource - how to query username - the authorities of a username NB: Don't scan the config package in the main config class. Instead, force the import of the security class config into it. `@Import(SecurityConfiguration.class)` NB: {noop}: no encodage #### Java methods security - To enable handling of security annotations `@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)` ### Security Tests `@WithUserDetails("toto@tata.fr")` `@MockUser` ## Spring Boot ### Les starters | Starters | Description | | -------------------------------- | ------------------------------------------------- | | **spring-boot-starter-web** | Développer une application web | | **spring-boot-starter-data-jpa** | Accéder à la base de données via JPA/Spring Data | | **spring-boot-starter-security** | Sécuriser l'application via spring security | | **spring-boot-starter-test** | Tester votre application avec Spring | --> Actuator Plus 1 plugin ### Conditional `@Conditional` -> ... `@Conditional(ConditionalProfile.class)` Classe d'autoconfiguration `AutoConfigurationBlabla` Conf per environement ### Tests ```java= @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) @AutoConfigureMockMvc ``` ## Spring Data --> Beaucoup de connecteurs pour les bdd noSQL Plus besoin d'implémenter le Repository !! `extends JpaRepository<TodoList, String>` ++ `@Enable....` on Configuration class ## Spring WebFlux Parallel to Spring Web MVC, Spring Framework 5.0 introduced a reactive-stack web framework whose name, “Spring WebFlux,”.

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully