Guide de Demarrage Rapide
Ce guide vous permet de demarrer votre projet final rapidement.
1. Creation du Projet
Avec Spring Initializr
-
Aller sur https://start.spring.io
-
Configurer:
- Project: Maven
- Language: Java
- Spring Boot: 3.2.x
- Group: com.example
- Artifact: projet-final
- Packaging: Jar
- Java: 21
-
Ajouter les dependances:
- Spring Web
- Spring Data JPA
- Spring Security
- Validation
- Lombok
- PostgreSQL Driver
- H2 Database (dev)
-
Telecharger et extraire
Structure Initiale
projet-final/
├── src/main/java/com/example/projet/
│ └── ProjetFinalApplication.java
├── src/main/resources/
│ └── application.properties
├── src/test/java/
└── pom.xml
2. Configuration de Base
pom.xml - Dependances Essentielles
<dependencies>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>0.12.3</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<!-- H2 (dev) -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<!-- PostgreSQL (prod) -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
application.yml
spring:
profiles:
active: dev
---
spring:
config:
activate:
on-profile: dev
datasource:
url: jdbc:h2:mem:devdb
driver-class-name: org.h2.Driver
username: sa
password:
h2:
console:
enabled: true
path: /h2-console
jpa:
hibernate:
ddl-auto: create-drop
show-sql: true
---
spring:
config:
activate:
on-profile: prod
datasource:
url: jdbc:postgresql://localhost:5432/projet
username: ${DB_USERNAME}
password: ${DB_PASSWORD}
jpa:
hibernate:
ddl-auto: validate
---
# Common config
app:
jwt:
secret: ${JWT_SECRET:votre-secret-de-256-bits-minimum-pour-hs256}
expiration: 86400000
3. Squelette de Base
User Entity
package com.example.projet.model;
import jakarta.persistence.*;
import lombok.*;
import java.time.LocalDateTime;
@Entity
@Table(name = "users")
@Getter @Setter
@NoArgsConstructor @AllArgsConstructor
@Builder
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
private String firstName;
private String lastName;
@Enumerated(EnumType.STRING)
private Role role;
private LocalDateTime createdAt;
@PrePersist
protected void onCreate() {
createdAt = LocalDateTime.now();
}
public enum Role {
ADMIN, USER
}
}
User Repository
package com.example.projet.repository;
import com.example.projet.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
boolean existsByEmail(String email);
}
Security Config
package com.example.projet.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.csrf(csrf -> csrf.disable())
.sessionManagement(session ->
session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated()
)
.headers(headers -> headers.frameOptions().disable());
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authenticationManager(
AuthenticationConfiguration config) throws Exception {
return config.getAuthenticationManager();
}
}
Auth Controller
package com.example.projet.controller;
import com.example.projet.dto.LoginRequest;
import com.example.projet.dto.RegisterRequest;
import com.example.projet.dto.AuthResponse;
import com.example.projet.service.AuthService;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/auth")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("/register")
public ResponseEntity<AuthResponse> register(@Valid @RequestBody RegisterRequest request) {
return ResponseEntity.ok(authService.register(request));
}
@PostMapping("/login")
public ResponseEntity<AuthResponse> login(@Valid @RequestBody LoginRequest request) {
return ResponseEntity.ok(authService.login(request));
}
}
4. Commandes Utiles
Execution
# Developement
./mvnw spring-boot:run
# Avec profil
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev
# Build
./mvnw clean package -DskipTests
# Run JAR
java -jar target/projet-final-0.0.1-SNAPSHOT.jar
Tests
# Tous les tests
./mvnw test
# Tests specifiques
./mvnw test -Dtest=UserServiceTest
# Avec couverture
./mvnw test jacoco:report
Base de Donnees
# H2 Console
http://localhost:8080/h2-console
# JDBC URL: jdbc:h2:mem:devdb
# Username: sa
# Password: (vide)
5. Checklist Demarrage
- Projet cree avec Spring Initializr
- Dependances ajoutees au pom.xml
- application.yml configure
- Entity User creee
- Repository User cree
- Security configuree
- Endpoint /api/auth/register fonctionne
- Endpoint /api/auth/login fonctionne
- Tests de base passent
6. Prochaines Etapes
- Ajouter les entites specifiques a votre projet
- Implementer les services metier
- Creer les controllers REST
- Ajouter la validation
- Implementer les tests
- Documenter l'API