Spring Boot: Creation,Dépendances et Configuration
Architecture d'une Application Spring Boot
Client
- Représente l'application frontale (web ou mobile) qui envoie des requêtes HTTP.
API Gateway
- Point d'entrée pour toutes les requêtes des clients. Il redirige les requêtes vers les services appropriés.
Spring Boot Application
- Le cœur de l'application contenant la logique métier, comprenant :
- Controllers : Gèrent les requêtes entrantes et les réponses.
- Services : Contiennent la logique métier et interagissent avec les Repositories .
- Repositories : Gèrent l'accès aux données et les interactions avec la base de données.
- Le cœur de l'application contenant la logique métier, comprenant :
Database
- Solution de stockage persistant pour les données de l'application (ex. : MySQL, PostgreSQL).
Microservices
- Services indépendants offrant des fonctionnalités spécifiques, pouvant être développés et déployés séparément.
Auth Server
- Responsable de l'authentification et de l'autorisation, génère et valide les jetons d'accès.
Cache
- Mécanisme de stockage des données fréquemment consultées en mémoire, améliorant les performances.
Message Broker
- Facilite la communication asynchrone entre les composants ou microservices (ex. : RabbitMQ, Kafka).
Database Queries
- Interactions entre l'application Spring Boot et la base de données pour les opérations CRUD.
Résumé
L'architecture est conçue pour favoriser la séparation des préoccupations, permettant une maintenance, une évolutivité et une flexibilité plus faciles dans le développement et le déploiement d'applications. Chaque composant interagit avec les autres pour offrir une expérience fluide à l'utilisateur final tout en assurant des opérations sécurisées, efficaces et fiables.
Implementing: Client → Gateway → Spring Boot App → Microservices, Cache, DB, Auth Server
📁 Project Structure
api-gateway— Routes requestsspring-boot-app— Main application (calls microservices, cache, DB, auth)microservice-a— Example microservicecache-server— Redis (optional)database— H2 or MySQLauth-server— OAuth2 server
Step 1: Create API Gateway
📁 File: api-gateway/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.bbank</groupId>
<artifactId>api-gateway</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>api-gateway</name>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
📁 File: api-gateway/src/main/resources/application.yml
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
- id: spring-boot-app
uri: lb://spring-boot-app
predicates:
- Path=/api/**
- id: microservice-a
uri: lb://microservice-a
predicates:
- Path=/msa/**
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
📁 File: api-gateway/src/main/java/com/bbank/apigateway/ApiGatewayApplication.java
package com.bbank.apigateway;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(ApiGatewayApplication.class, args);
}
}
Step 2: Create Spring Boot Application
📁 File: spring-boot-app/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.bbank</groupId>
<artifactId>spring-boot-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-app</name>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
📁 File: spring-boot-app/src/main/resources/application.yml
server:
port: 8081
spring:
application:
name: spring-boot-app
datasource:
url: jdbc:h2:mem:bbank-db
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: update
show-sql: true
cache:
type: simple
feign:
client:
config:
default:
connectTimeout: 5000
readTimeout: 5000
security:
oauth2:
resourceserver:
jwt:
issuer-uri: http://localhost:9000/oauth2/token
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/model/User.java
package com.bbank.springbootapp.model;
import jakarta.persistence.*;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String email;
// Constructors
public User() {}
public User(String name, String email) {
this.name = name;
this.email = email;
}
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; }
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/repository/UserRepository.java
package com.bbank.springbootapp.repository;
import com.bbank.springbootapp.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/service/UserService.java
package com.bbank.springbootapp.service;
import com.bbank.springbootapp.model.User;
import com.bbank.springbootapp.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
@Cacheable(value = "users", key = "#email")
public User getUserByEmail(String email) {
return userRepository.findByEmail(email);
}
public User saveUser(User user) {
return userRepository.save(user);
}
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/controller/UserController.java
package com.bbank.springbootapp.controller;
import com.bbank.springbootapp.model.User;
import com.bbank.springbootapp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/{email}")
public User getUser(@PathVariable String email) {
return userService.getUserByEmail(email);
}
@PostMapping
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/config/SecurityConfig.java
package com.bbank.springbootapp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeHttpRequests(authz -> authz
.requestMatchers("/api/users/**").authenticated()
.anyRequest().permitAll()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(jwt -> jwt
.jwtAuthenticationConverter(jwtAuthenticationConverter())
)
);
return http.build();
}
@Bean
public JwtAuthenticationConverter jwtAuthenticationConverter() {
JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
converter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
return converter;
}
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/client/MicroserviceAClient.java
package com.bbank.springbootapp.client;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@FeignClient(name = "microservice-a")
public interface MicroserviceAClient {
@GetMapping("/msa/data/{id}")
String getData(@PathVariable Long id);
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/service/MicroserviceAService.java
package com.bbank.springbootapp.service;
import com.bbank.springbootapp.client.MicroserviceAClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class MicroserviceAService {
@Autowired
private MicroserviceAClient microserviceAClient;
public String callMicroserviceA(Long id) {
return microserviceAClient.getData(id);
}
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/controller/IntegrationController.java
package com.bbank.springbootapp.controller;
import com.bbank.springbootapp.service.MicroserviceAService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/integration")
public class IntegrationController {
@Autowired
private MicroserviceAService microserviceAService;
@GetMapping("/call-msa/{id}")
public String callMicroserviceA(@PathVariable Long id) {
return microserviceAService.callMicroserviceA(id);
}
}
📁 File: spring-boot-app/src/main/java/com/bbank/springbootapp/SpringBootApplication.java
package com.bbank.springbootapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class SpringBootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplication.class, args);
}
}
Step 3: Create Microservice A
📁 File: microservice-a/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.bbank</groupId>
<artifactId>microservice-a</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>microservice-a</name>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
📁 File: microservice-a/src/main/resources/application.yml
server:
port: 8082
spring:
application:
name: microservice-a
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
📁 File: microservice-a/src/main/java/com/bbank/microservicea/MicroserviceAApplication.java
package com.bbank.microservicea;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class MicroserviceAApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceAApplication.class, args);
}
}
📁 File: microservice-a/src/main/java/com/bbank/microservicea/controller/DataController.java
package com.bbank.microservicea.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class DataController {
@GetMapping("/data/{id}")
public String getData(@PathVariable Long id) {
return "Data from Microservice A for ID: " + id;
}
}
Step 4: Create Auth Server (OAuth2)
📁 File: auth-server/pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.5</version>
<relativePath/>
</parent>
<groupId>com.bbank</groupId>
<artifactId>auth-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>auth-server</name>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2023.0.1</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
📁 File: auth-server/src/main/resources/application.yml
server:
port: 9000
spring:
application:
name: auth-server
datasource:
url: jdbc:h2:mem:auth-db
driver-class-name: org.h2.Driver
username: sa
password:
jpa:
hibernate:
ddl-auto: update
show-sql: true
security:
oauth2:
authorization-server:
issue-token:
access-token:
value-creator: org.springframework.security.oauth2.server.authorization.token.DefaultAccessTokenValueCreator
client:
- client-id: myclient
client-secret: mysecret
scopes:
- read
- write
authorities:
- ROLE_USER
redirect-uri: "http://localhost:8081/login"
post-logout-redirect-uri: "http://localhost:8081/logout"
grant-types:
- authorization_code
- refresh_token
- client_credentials
secret: mysecret
token-settings:
access-token-time-to-live: 3600
refresh-token-time-to-live: 86400
📁 File: auth-server/src/main/java/com/bbank/authserver/AuthServerApplication.java
package com.bbank.authserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class AuthServerApplication {
public static void main(String[] args) {
SpringApplication.run(AuthServerApplication.class, args);
}
}
✅ Step 5: Run & Test
▶️ Start Order:
- Start Eureka Server → http://localhost:8761
- Start Auth Server → http://localhost:9000
- Start Microservice A
- Start Spring Boot App
- Start API Gateway → http://localhost:8080
🧪 Test via Gateway:
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d "{ \"name\": \"John Doe\", \"email\": \"john@example.com\" }"
curl -X GET http://localhost:8080/api/users/john@example.com \
-H "Authorization: Bearer YOUR_TOKEN"
curl -X GET http://localhost:8080/api/integration/call-msa/123 \
-H "Authorization: Bearer YOUR_TOKEN"
- Client → Gateway → Spring Boot App → Microservices, Cache, DB, Auth
- Caching with `@Cacheable`
- Database with JPA/H2
- Authentication with OAuth2
- Service calls via Feign
Les étapes à suivre
- 1Création d'un projet SpringBoot avec initializr
- 2Choix des dépendaces du fichier pom.xml
- 3Télécher puis importer le projet dans Eclipse
- 4Configuration du fichier properties.json
- 5Créer la base de données
1.Création d'un projet SpringBoot avec initializr
Spring Initializr est une application Web qui permet de générer la structure un projet Spring Boot et ajouter les dépendances du projet le site web de l'application: https://start.spring.io
2.Spring Initializr permet de choisir les dépendances qui seront utilisées dans le projet :
-
Spring Web
Créez des applications Web, y compris RESTful, à l'aide de Spring MVC. Utilise Apache Tomcat comme conteneur intégré par défaut.
-
Spring Data JPA
Conservez les données dans les base de données SQL avec l'API Java Persistence en utilisant Spring Data et Hibernate.
-
Driver MySQL
Pilote MySQL JDBC.
-
Spring Boot DevTools
Fournit des redémarrages rapides des applications, LiveReload et des configurations pour une expérience de développement améliorée.
3.Télécher puis importer le projet dans Eclipse
Une fois le projet est créer on doit le télécharger pour l'inporter dans eclipseExtraire le projet puis ouvrir eclipse ->File->import->maven Project->existing maven project->chosir ton projet ->next finish
5.Configuration du fichier properties.json
resources/properties.json est un fichier de configuration de projet permet de déclarer un ensembles de beans qui seront utilsés par Spring ioc pour instancer des objets lorsque on utilise l'annoation @Autowired exemples:
Explications:
#activation de ddl data definition language6.Créer la base de données
dans le fichier de configuration properties.json on a met mysql://localhost:3306/springbootDB donc il faut créer la base de données
springbootDB dans MySQL