0% found this document useful (0 votes)
67 views

Spring Course 2024v2

This document provides an overview of the Spring framework. It discusses what Spring is, its core components like beans and dependency injection, how to create RESTful web APIs and use Spring MVC. It also introduces Spring Boot and how it simplifies creating standalone Spring applications.

Uploaded by

Soltan Sadok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
67 views

Spring Course 2024v2

This document provides an overview of the Spring framework. It discusses what Spring is, its core components like beans and dependency injection, how to create RESTful web APIs and use Spring MVC. It also introduces Spring Boot and how it simplifies creating standalone Spring applications.

Uploaded by

Soltan Sadok
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Chapter 1.

Spring

I. Introduction
Spring is a Java framework for building web applications.

Spring has several libraries (or projects), such as:

- Spring Boot: Takes an opinionated view of building Spring applications and gets you up and
running as quickly as possible.
- Spring Framework: Provides core support for dependency injection, transaction management,
web apps, data access, messaging, and more.
- Spring Data: Provides a consistent approach to data access – relational, non-relational, map-
reduce, and beyond.
- Spring Cloud: Provides a set of tools for common patterns in distributed systems. Useful for
building and deploying microservices.
- Spring Cloud Data Flow: Provides an orchestration service for composable data microservice
applications on modern runtimes.
- Spring Security: Protects your application with comprehensive and extensible authentication
and authorization support.
- Spring Authorization Server: Provides a secure, light-weight, and customizable foundation for
building OpenID Connect 1.0 Identity Providers and OAuth2 Authorization Server products.
- Spring for GraphQL: Spring for GraphQL provides support for Spring applications built on
GraphQL Java.
- Spring Session: Provides an API and implementations for managing a user’s session information.
- Spring Integration: Supports the well-known Enterprise Integration Patterns through lightweight
messaging and declarative adapters.
- Spring Web Services: Facilitates the development of contract-first SOAP web services.

See: https://spring.io/projects

 The term "Spring" means different things in different contexts. It can be used to refer to the
Spring Framework project itself. Most often, when people say "Spring", they mean the entire
family of projects. (link: https://docs.spring.io/spring-framework/reference/overview.html)

1
II. Spring Framework
The current version of Spring Framework is 6.1.3. As of Spring Framework 6.0, Spring requires Java 17+.

Spring supports different programming languages: Java, Kotlin and Groovy.

The Spring Framework uses Beans. It supports the Dependency Injection and Common Annotations.

Features:

 Core technologies: dependency injection, events, resources, i18n, validation, data binding, type
conversion, SpEL, AOP.

 Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient.

 Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.

 Spring MVC and Spring WebFlux web frameworks.

 Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache and observability.

 Languages: Kotlin, Groovy, dynamic languages.

1. Annotations

An annotation looks like the following:

@Entity

The at sign character (@) indicates to the compiler that what follows is an annotation. In the following
example, the annotation's name is Override:

@Override
void mySuperMethod() {
}

2
The annotation can include elements, which can be named or unnamed, and there are values for those
elements:

@Author(name = "Ali Dridi", date = "3/27/2003")


class MyClass {
}

or

@SuppressWarnings(value = "unchecked")
void myMethod() {
}

If there is just one element named value, then the name can be omitted, as in:

@SuppressWarnings("unchecked")
void myMethod() {
}

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous
@Override example.

It is also possible to use multiple annotations on the same declaration:

@Author(name = "Jane Doe")


@EBook
class MyClass {
}

The annotation type can be one of the types that are already defined. In the previous examples,
Override and SuppressWarnings are predefined Java annotations. It is also possible to define your own
annotation type. The Author and Ebook annotations in the previous example are custom annotations.

Where Annotations Can Be Used

Annotations can be applied to declarations: declarations of classes, fields, methods, and other program
elements.

3
2. Beans

A Spring Application is composed of components. These components are called “beans”.

There are several types of beans: @Component, @Service, @Repository, @Controller,


@RestController and others.

The following example shows a @RestController Bean:

@RestController
public class HomeController {
@GetMapping
public String index() {
return "hello world";
}
}

 To scan and register the application beans, it is necessary to add @ComponentScan or


@SpringBootApplication annotation (which implicitly includes @ComponentScan) to the main
class (the application class)
 The main class should be located in a top package

Example:

@SpringBootApplication
public class WebapiApplication {
public static void main(String[] args) {
SpringApplication.run(WebapiApplication.class, args);
}
}

3. Dependency injection

Dependency injection (DI) is a process where objects define their dependencies (that is, the other
objects they need). The container then injects those dependencies when it creates the bean.

4
A class can define its dependencies in different ways:

- constructor arguments
- arguments to a method, or
- fields annotated with @Autowired

Constructor-based Dependency Injection

Constructor-based DI is accomplished by the container invoking a constructor with a number of


arguments, each representing a dependency. The following example shows a class that can be
dependency-injected with constructor injection:

public class SimpleMovieLister {


// the SimpleMovieLister has a dependency on a MovieFinder
private final MovieFinder movieFinder;

// a constructor so that the Spring container can inject a MovieFinder


public SimpleMovieLister(MovieFinder movieFinder) {
this.movieFinder = movieFinder;
}
}

Annotation-based Dependency Injection

The following example shows a class that can be dependency-injected with @Autowired annotation:

public class SimpleMovieLister {


@Autowired
private final MovieFinder movieFinder;
}

4. RESTful web API

Spring is mainly used to create REST Web Services (RESTful Web API). It lets you create special
@RestController beans to handle incoming HTTP requests. Methods in your controller are mapped to
HTTP by using @RequestMapping annotations.

The following code shows a typical @RestController that serves JSON data:

5
@RestController
@RequestMapping("/users")
public class MyRestController {
private final UserRepository userRepository;

public MyRestController(UserRepository userRepository) {


this.userRepository = userRepository;
}

@GetMapping
public List<User> getUsers() {
return this.userRepository.findAll();
}

@GetMapping("/{userId}")
public User getUser(@PathVariable Long userId) {
return this.userRepository.findById(userId).get();
}

@PostMapping
public void createUser(@RequestBody User user) {
// create user
}

@PutMapping("/{userId}")
public User updateUser(@PathVariable Long userId, @RequestBody User user)
{
// update user
}

@DeleteMapping("/{userId}")
public void deleteUser(@PathVariable Long userId) {
this.userRepository.deleteById(userId);
}
}

5. Spring MVC

The Spring Web MVC framework (often referred to as “Spring MVC”) is a rich “model view controller”
web framework.

Spring MVC lets you create special @Controller or @RestController beans to handle incoming HTTP
requests.

6
Spring MVC allows us to serve dynamic HTML content. It supports a variety of templating technologies,
including:

- Thymeleaf
- JSP
- FreeMarker
- Groovy
- Mustache

 If possible, JSPs should be avoided. There are several known limitations when using them with
embedded servlet containers.

When you use one of these templating engines with the default configuration, your templates are
picked up automatically from src/main/resources/templates.

III. Spring Boot


Link: https://spring.io/projects/spring-boot

Spring Boot makes it easy to create Spring based Applications that you can "just run".

Most Spring Boot applications need minimal Spring configuration.

Features

- Create stand-alone Spring applications


- Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)
- Provide opinionated 'starter' dependencies to simplify your build configuration
- Automatically configure Spring and 3rd party libraries whenever possible
- Provide production-ready features such as metrics, health checks, and externalized
configuration
- Absolutely no code generation and no requirement for XML configuration

Getting Started

- Super quick — try the Quickstart Guide.


- More general — try Building an Application with Spring Boot
- More specific — try Building a RESTful Web Service.
- Or search through all our guides on the Guides homepage.

7
1. Create new project

The easiest way to create a new project is using Spring initializr: https://start.spring.io/

We choose Maven as the project building tool, and Java as the programming language

Select the Spring boot version

Fill the project metadata:

- Group : name of the application owner (or his reversed domain name)
- Artifact: the application name (Artifact = Name)

The selected Java version should be installed on your computer

Add the project dependencies based on your needs

Generate the Zip file, extract it and open it using your IDE

8
2. Project Structure

Required tools:

- IDE
o
IntelliJ IDE
o
Eclipse IDE for Enterprise Java and Web Developers:
https://www.eclipse.org/downloads/packages/
o VS Code + Java Extension Pack + Spring Boot Extension Pack
- Postman

9
TP 1

1) Installer les outils suivants :


a. Installer l’IDE de votre choix parmi les options suivantes : Eclipse Enterprise, IntelliJ
IDEA ou VS Code. Dans le cas de VS Code, il faut installer l’extension « Extension Pack
for Java » et s’assurer que la JDK Java est installée (version minimale 17)
b. Postman

2) Créer un nouveau projet Spring Boot avec Spring initializr :


a. Group : com.fsm
b. Artifact : webapi
c. Dépendances : Spring Web + Spring Boot DevTools

3) Ouvrir le projet avec un IDE et créer les packages « controllers » (com.fsm.webapi.controllers)


et « services » (com.fsm.webapi.services)

4) Créer un RestController dans le package « controllers » et nommer le « HomeController ». Il


doit être accessible à l’url « /home ». Remarque : un RestController est une classe Java annotée
par @RestController.

5) Créer 4 méthodes publiques dans « HomeController » :


a. Ces méthodes doivent être accessibles à l’url « /home » en utilisant les 4 méthodes
http : Get, Post, Put et Delete.
b. Chaque méthode retourne une chaine de caractères avec le nom de la méthodes http
utilisée (Get, Post, Put ou Delete)

6) Créer la classe « LogHelper » dans le package « services » :


a. Enregistrer cette classe en tant que bean de type service (la classe doit être annotée par
@Service)
b. Créer la méthode publique log() qui permet d’afficher la date sur la console

7) Injecter l’objet « LogHelper » dans le contrôleur « HomeController » en utilisant l’annotation


@Autowired. Utiliser cet objet dans les différentes méthodes du contrôleur.

10

You might also like