Plateforme de révision : cours, exemples de code, quiz, définitions et section examen de demain.
Qu'est-ce que Spring Boot, auto-configuration, starters, @SpringBootApplication, embedded server.
IoC Container, @Autowired, @Component, @Service, @Repository, @Controller, @Bean, scopes.
@Entity, @Repository, JpaRepository, JPQL, associations (OneToMany, ManyToMany), findByKeyword.
Aspect Oriented Programming, @Aspect, @Before, @After, @Around, Pointcut, JoinPoint.
Data Transfer Object, MapStruct, ModelMapper, séparation couches, avantages des DTOs.
@Scheduled, cron expressions, fixedRate, fixedDelay, @EnableScheduling.
Associations, affectation/désaffectation, JPQL, Scheduler, 5 entités, Repo+Service+Controller, DTO, Maven, définitions.
Spring Boot est un framework Java basé sur Spring Framework qui simplifie la création d'applications standalone, prêtes pour la production. Il élimine la configuration XML manuelle grâce à l'auto-configuration.
@SpringBootApplication // = @Configuration + @EnableAutoConfiguration + @ComponentScan public class MonApplication { public static void main(String[] args) { SpringApplication.run(MonApplication.class, args); } }
src/ ├── main/ │ ├── java/com/example/ │ │ ├── entities/ // Entités JPA │ │ ├── repositories/ // Interfaces Repository │ │ ├── services/ // Logique métier │ │ ├── controllers/ // REST Controllers │ │ └── dto/ // Data Transfer Objects │ └── resources/ │ └── application.properties └── test/
spring.datasource.url=jdbc:mysql://localhost:3306/mabd spring.datasource.username=root spring.datasource.password= spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> </parent> <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>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency> </dependencies>
| Annotation | Couche | Rôle |
|---|---|---|
@Component | Générique | Bean Spring générique |
@Service | Service | Logique métier |
@Repository | Persistance | Accès données + gestion exceptions JPA |
@Controller | Web | Contrôleur MVC (vues) |
@RestController | Web | @Controller + @ResponseBody (JSON/XML) |
@Configuration | Config | Classe de configuration, définit des @Bean |
// 1. Injection par constructeur (recommandée) @Service public class ActeurService { private final ActeurRepository repo; public ActeurService(ActeurRepository repo) { // Spring injecte auto this.repo = repo; } } // 2. Injection par champ (simple mais moins testable) @Service public class ActeurService { @Autowired private ActeurRepository repo; } // 3. Injection par setter @Autowired public void setRepo(ActeurRepository repo) { this.repo = repo; }
@Configuration public class AppConfig { @Bean public ModelMapper modelMapper() { return new ModelMapper(); } }
| Scope | Description |
|---|---|
singleton | Par défaut — une seule instance partagée |
prototype | Nouvelle instance à chaque injection |
request | Une instance par requête HTTP |
session | Une instance par session HTTP |
@Entity @Table(name = "acteurs") public class Acteur { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String nom; private String nationalite; // Getters / Setters / Constructeurs }
@Repository public interface ActeurRepository extends JpaRepository<Acteur, Long> { // Méthodes dérivées (Spring génère le SQL automatiquement) List<Acteur> findByNom(String nom); List<Acteur> findByNomContaining(String keyword); List<Acteur> findByNationalite(String nationalite); // Requête JPQL personnalisée @Query("SELECT a FROM Acteur a WHERE a.nom LIKE %:keyword%") List<Acteur> searchByKeyword(@Param("keyword") String keyword); }
// OneToMany — Un Projet a plusieurs Acteurs @Entity public class Projet { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String titre; @ManyToMany @JoinTable( name = "projet_acteur", joinColumns = @JoinColumn(name = "projet_id"), inverseJoinColumns = @JoinColumn(name = "acteur_id") ) private List<Acteur> acteurs = new ArrayList<>(); } @Entity public class Acteur { @ManyToMany(mappedBy = "acteurs") private List<Projet> projets = new ArrayList<>(); }
@Service @Transactional public class ProjetService { @Autowired private ProjetRepository projetRepo; @Autowired private ActeurRepository acteurRepo; // Affecter un acteur à un projet public void affecter(Long projetId, Long acteurId) { Projet projet = projetRepo.findById(projetId).orElseThrow(); Acteur acteur = acteurRepo.findById(acteurId).orElseThrow(); projet.getActeurs().add(acteur); projetRepo.save(projet); } // Désaffecter un acteur d'un projet public void desaffecter(Long projetId, Long acteurId) { Projet projet = projetRepo.findById(projetId).orElseThrow(); projet.getActeurs().removeIf(a -> a.getId().equals(acteurId)); projetRepo.save(projet); } // Recherche par mot-clé public List<Projet> searchByKeyword(String keyword) { return projetRepo.findByTitreContaining(keyword); } }
@RestController @RequestMapping("/api/projets") public class ProjetController { @Autowired private ProjetService service; @GetMapping public List<Projet> list() { return service.findAll(); } @PostMapping public Projet create(@RequestBody Projet p) { return service.save(p); } @PutMapping("/{projetId}/acteurs/{acteurId}") public void affecter(@PathVariable Long projetId, @PathVariable Long acteurId) { service.affecter(projetId, acteurId); } @DeleteMapping("/{projetId}/acteurs/{acteurId}") public void desaffecter(@PathVariable Long projetId, @PathVariable Long acteurId) { service.desaffecter(projetId, acteurId); } @GetMapping("/search") public List<Projet> search(@RequestParam String keyword) { return service.searchByKeyword(keyword); } }
// JPQL utilise les noms des CLASSES et ATTRIBUTS Java (pas les tables SQL) @Query("SELECT a FROM Acteur a WHERE a.nationalite = :nat") List<Acteur> findByNationalite(@Param("nat") String nat); @Query("SELECT p FROM Projet p JOIN p.acteurs a WHERE a.id = :acteurId") List<Projet> findProjetsByActeur(@Param("acteurId") Long id); @Query("SELECT a FROM Acteur a WHERE LOWER(a.nom) LIKE LOWER(CONCAT('%',:kw,'%'))") List<Acteur> searchActeurs(@Param("kw") String kw);
| Terme | Définition |
|---|---|
| Aspect | Module qui encapsule une préoccupation transversale (logging, sécurité...) |
| Advice | Le code à exécuter (Before, After, Around...) |
| Pointcut | Expression qui sélectionne les JoinPoints où s'applique l'advice |
| JoinPoint | Point d'exécution du programme (appel de méthode) |
| Weaving | Processus qui lie l'aspect au code cible |
@Aspect @Component public class LoggingAspect { // Avant toute méthode dans le package services @Before("execution(* com.example.services.*.*(..))") public void beforeMethod(JoinPoint jp) { System.out.println("Appel : " + jp.getSignature().getName()); } // Après exécution (succès ou exception) @After("execution(* com.example.services.*.*(..))") public void afterMethod(JoinPoint jp) { System.out.println("Fin : " + jp.getSignature().getName()); } // Autour de la méthode (contrôle complet) @Around("execution(* com.example.services.*.*(..))") public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable { long start = System.currentTimeMillis(); Object result = pjp.proceed(); // Appel de la méthode réelle long duration = System.currentTimeMillis() - start; System.out.println("Durée : " + duration + "ms"); return result; } // Seulement si succès @AfterReturning(pointcut = "execution(* com.example.services.*.*(..))", returning = "result") public void afterSuccess(JoinPoint jp, Object result) { } // Seulement si exception @AfterThrowing(pointcut = "execution(* com.example.services.*.*(..))", throwing = "ex") public void afterError(JoinPoint jp, Exception ex) { } }
"execution(* com.example.services.*.*(..))" // ^ ^^^^^^^^^^^^^^^^^^^^^^^ ^ ^^^ // | package.classe | args (..= tous) // retour méthode (*=toutes)
spring-boot-starter-aopUn Data Transfer Object est un objet simple qui transporte des données entre les couches sans logique métier. Il découple l'API externe de la structure interne des entités.
// Entité (avec mdp, données internes...) @Entity public class Acteur { private Long id; private String nom; private String motDePasse; // Ne pas exposer ! private List<Projet> projets; } // DTO (seulement ce dont le client a besoin) public class ActeurDTO { private Long id; private String nom; private String nationalite; // Getters, Setters, Constructeurs }
@Component public class ActeurMapper { public ActeurDTO toDTO(Acteur acteur) { ActeurDTO dto = new ActeurDTO(); dto.setId(acteur.getId()); dto.setNom(acteur.getNom()); dto.setNationalite(acteur.getNationalite()); return dto; } public Acteur toEntity(ActeurDTO dto) { Acteur a = new Acteur(); a.setNom(dto.getNom()); a.setNationalite(dto.getNationalite()); return a; } }
// Dans pom.xml : // <dependency><groupId>org.modelmapper</groupId><artifactId>modelmapper</artifactId></dependency> @Bean public ModelMapper modelMapper() { return new ModelMapper(); } // Utilisation dans le service : @Autowired private ModelMapper mapper; ActeurDTO dto = mapper.map(acteur, ActeurDTO.class); Acteur entity = mapper.map(dto, Acteur.class);
@Service public class ActeurService { @Autowired private ActeurRepository repo; @Autowired private ModelMapper mapper; public List<ActeurDTO> findAll() { return repo.findAll().stream() .map(a -> mapper.map(a, ActeurDTO.class)) .collect(Collectors.toList()); } public ActeurDTO save(ActeurDTO dto) { Acteur entity = mapper.map(dto, Acteur.class); return mapper.map(repo.save(entity), ActeurDTO.class); } }
@SpringBootApplication @EnableScheduling // OBLIGATOIRE pour activer les tâches planifiées public class Application { ... }
| Attribut | Description | Exemple |
|---|---|---|
fixedRate | Exécute toutes les N ms (depuis le début de la dernière) | fixedRate = 5000 |
fixedDelay | Attend N ms après la fin de la dernière exécution | fixedDelay = 3000 |
cron | Expression cron (planification précise) | cron = "0 0 8 * * ?" |
initialDelay | Délai avant la première exécution | initialDelay = 1000 |
// Format : seconde minute heure jour-du-mois mois jour-de-semaine // 0-59 0-59 0-23 1-31 1-12 0-7 (0=Dimanche) "0 0 8 * * ?" // Tous les jours à 8h00 "0 30 9 * * MON" // Tous les lundis à 9h30 "0 0 0 1 * ?" // Le 1er de chaque mois à minuit "0 0/15 * * * ?" // Toutes les 15 minutes "0 0 8-18 * * ?" // Toutes les heures de 8h à 18h
@Component public class MonScheduler { @Autowired private ProjetService projetService; // Tous les jours à 8h00 @Scheduled(cron = "0 0 8 * * ?") public void envoyerRapportQuotidien() { List<Projet> projets = projetService.findAll(); System.out.println("Rapport quotidien : " + projets.size() + " projets"); // Logique d'envoi email, notification, etc. } // Toutes les 5 secondes @Scheduled(fixedRate = 5000) public void verifierEtat() { System.out.println("Vérification état : " + new Date()); } // Attendre 3s après la fin de la tâche précédente @Scheduled(fixedDelay = 3000, initialDelay = 1000) public void nettoyage() { System.out.println("Nettoyage effectué"); } }
@EnableScheduling, les méthodes @Scheduled ne s'exécutent PAS — erreur classique d'examen !Testez vos connaissances sur tous les chapitres.
@Query("SELECT a FROM Acteur a WHERE a.nom LIKE %:keyword%")
List<Acteur> searchByKeyword(@Param("keyword") String keyword);@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.services.*.*(..))")
public void logBefore(JoinPoint jp) {
System.out.println("Appel : " + jp.getSignature().getName());
}
}La gestion des associations entre entités, l'ajout/suppression dans la liste et le save() sont systématiquement demandés.
save() après avoir modifié la liste !Écrire une requête JPQL personnalisée avec paramètre nommé. Attention : noms des CLASSES Java, pas des tables SQL.
Syntaxe cron : "0 0 8 * * ?" = tous les jours à 8h. Ne pas oublier @EnableScheduling sur la classe principale.
Écrire les 3 couches complètes pour une entité donnée. Savoir quelle annotation va où.
Questions de définition courtes. Connaître les différences : @Component vs @Service vs @Repository.
Lister 3-5 avantages. Apprendre les mots-clés : auto-configuration, couplage faible, testabilité, sécurité...
Méthode dérivée Spring Data ou @Query JPQL, puis appel dans le service et exposition via @GetMapping avec @RequestParam.
5 classes Entity + Repo + Service + Controller pour chaque
// Exemple : Acteur, Projet, Film, Role, Studio (5 entités) // entities/Acteur.java @Entity public class Acteur { @Id @GeneratedValue Long id; String nom; String nationalite; } // repositories/ActeurRepository.java @Repository public interface ActeurRepository extends JpaRepository<Acteur, Long> { } // services/ActeurService.java @Service public class ActeurService { @Autowired ActeurRepository repo; ... } // controllers/ActeurController.java @RestController @RequestMapping("/api/acteurs") public class ActeurController { ... }
// Service — affecter un acteur à un projet @Transactional public void affecterActeurAuProjet(Long projetId, Long acteurId) { Projet projet = projetRepo.findById(projetId) .orElseThrow(() -> new RuntimeException("Projet non trouvé")); Acteur acteur = acteurRepo.findById(acteurId) .orElseThrow(() -> new RuntimeException("Acteur non trouvé")); projet.getActeurs().add(acteur); // Ajout dans la liste projetRepo.save(projet); // OBLIGATOIRE pour persister } // Controller @PutMapping("/{projetId}/acteurs/{acteurId}") public ResponseEntity<Void> affecter(@PathVariable Long projetId, @PathVariable Long acteurId) { service.affecterActeurAuProjet(projetId, acteurId); return ResponseEntity.ok().build(); }
// Service public List<Acteur> getActeursOfProjet(Long projetId) { Projet projet = projetRepo.findById(projetId).orElseThrow(); return projet.getActeurs(); } public List<Projet> getProjetsOfActeur(Long acteurId) { Acteur acteur = acteurRepo.findById(acteurId).orElseThrow(); return acteur.getProjets(); } // Controller @GetMapping("/{projetId}/acteurs") public List<Acteur> listActeurs(@PathVariable Long projetId) { return service.getActeursOfProjet(projetId); } @GetMapping("/acteurs/{acteurId}/projets") public List<Projet> listProjets(@PathVariable Long acteurId) { return service.getProjetsOfActeur(acteurId); }
// Repository @Repository public interface ProjetRepository extends JpaRepository<Projet, Long> { // Méthode dérivée (Spring génère le SQL automatiquement) List<Projet> findByTitreContaining(String keyword); // OU avec JPQL personnalisée @Query("SELECT p FROM Projet p WHERE p.titre LIKE %:keyword%") List<Projet> searchByKeyword(@Param("keyword") String keyword); } // Service public List<Projet> searchByKeyword(String keyword) { return projetRepo.findByTitreContaining(keyword); } // Controller @GetMapping("/search") public List<Projet> search(@RequestParam String keyword) { return service.searchByKeyword(keyword); } // Appel : GET /api/projets/search?keyword=action
// JPQL = SQL mais sur les CLASSES Java, pas les tables // Sélection simple @Query("SELECT a FROM Acteur a WHERE a.nationalite = :nat") List<Acteur> findByNationalite(@Param("nat") String nat); // LIKE (recherche partielle) @Query("SELECT a FROM Acteur a WHERE a.nom LIKE %:keyword%") List<Acteur> searchActeurs(@Param("keyword") String keyword); // Jointure entre entités @Query("SELECT p FROM Projet p JOIN p.acteurs a WHERE a.id = :acteurId") List<Projet> findProjetsByActeur(@Param("acteurId") Long acteurId); // Plusieurs conditions @Query("SELECT a FROM Acteur a WHERE a.nationalite = :nat AND a.nom LIKE %:keyword%") List<Acteur> searchByNatAndKeyword(@Param("nat") String nat, @Param("keyword") String keyword);
// ÉTAPE 1 : Activer dans la classe principale @SpringBootApplication @EnableScheduling // ← NE PAS OUBLIER public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } // ÉTAPE 2 : Créer le composant Scheduler @Component public class ProjetScheduler { @Autowired private ProjetService projetService; // Tous les jours à 8h00 du matin @Scheduled(cron = "0 0 8 * * ?") public void tacheQuotidienne() { System.out.println("Tâche exécutée à : " + new Date()); List<Projet> projets = projetService.findAll(); System.out.println("Nombre de projets : " + projets.size()); // Logique métier : envoi rapport, nettoyage, notification... } // Tous les jours à 23h30 @Scheduled(cron = "0 30 23 * * ?") public void nettoyageQuotidien() { System.out.println("Nettoyage nocturne lancé..."); } } // Aide-mémoire Cron : // "0 0 8 * * ?" → sec=0 min=0 heure=8 tousLesjours // "0 0 9 * * MON" → Chaque lundi à 9h // "0 */30 * * * ?" → Toutes les 30 minutes
// Service — désaffecter un acteur d'un projet @Transactional public void desaffecterActeurDuProjet(Long projetId, Long acteurId) { Projet projet = projetRepo.findById(projetId) .orElseThrow(() -> new RuntimeException("Projet introuvable")); // Retirer l'acteur de la liste projet.getActeurs().removeIf(a -> a.getId().equals(acteurId)); // Sauvegarder projetRepo.save(projet); } // Controller @DeleteMapping("/{projetId}/acteurs/{acteurId}") public ResponseEntity<Void> desaffecter( @PathVariable Long projetId, @PathVariable Long acteurId) { service.desaffecterActeurDuProjet(projetId, acteurId); return ResponseEntity.noContent().build(); }
Outil de build et gestion de dépendances Java. Le pom.xml déclare les dépendances (starters Spring Boot). spring-boot-starter-parent gère les versions compatibles automatiquement.
Objet simple qui transporte des données entre couches ou vers l'API. Découple la structure de la BDD de l'API, sécurise (cache les champs sensibles), améliore les performances.
Le conteneur Spring crée et gère les objets (beans) à la place du développeur. Le code ne crée plus ses propres dépendances avec new.
Spring injecte automatiquement la dépendance correspondante (bean du même type) dans le champ ou constructeur annoté.
Langage de requête JPA orienté objet. Utilise les noms des classes Java et attributs (pas SQL). Utilisé avec @Query dans les repositories.
Délimite une transaction. Si une erreur survient, toutes les modifications de la méthode sont annulées (rollback). Obligatoire pour les opérations d'écriture complexes.