Chapitre 1: Annotations Core Spring
1. @SpringBootApplication
L'annotation de démarrage qui combine trois annotations en une.
@SpringBootApplication
public class MonApplication {
public static void main(String[] args) {
SpringApplication.run(MonApplication.class, args);
}
}
Équivalent à:
@SpringBootConfiguration // Indique une classe de configuration
@EnableAutoConfiguration // Active l'auto-configuration Spring Boot
@ComponentScan // Scanne les composants dans le package courant et sous-packages
2. Annotations de Stéréotype
Ces annotations identifient le rôle d'une classe dans l'architecture.
@Component
Annotation générique pour tout bean Spring.
@Component
public class EmailValidator {
public boolean isValid(String email) {
return email != null && email.contains("@");
}
}
@Service
Indique une classe de logique métier (couche service).
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public User findById(Long id) {
return userRepository.findById(id)
.orElseThrow(() -> new RuntimeException("User non trouvé"));
}
}
@Repository
Indique une classe d'accès aux données. Active la traduction automatique des exceptions SQL en exceptions Spring.
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByEmail(String email);
}
@Controller
Indique un contrôleur MVC (retourne des vues HTML).
@Controller
public class PageController {
@GetMapping("/accueil")
public String accueil(Model model) {
model.addAttribute("message", "Bienvenue!");
return "accueil"; // Retourne le nom d'une vue (template)
}
}
@RestController
Combinaison de @Controller + @ResponseBody. Chaque méthode retourne du JSON/XML directement.
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping
public List<User> getAll() {
return userService.findAll(); // Retourne du JSON automatiquement
}
}
Résumé des stéréotypes
| Annotation | Couche | Rôle |
|---|---|---|
@Component | Générique | Bean Spring quelconque |
@Service | Service | Logique métier |
@Repository | Données | Accès base de données |
@Controller | Web | Contrôleur MVC (vues) |
@RestController | Web | Contrôleur REST (JSON) |
3. Annotations d'Injection de Dépendances
@Autowired
Injection automatique d'un bean Spring.
@Service
public class OrderService {
// Injection par constructeur (RECOMMANDÉ)
private final ProductService productService;
@Autowired // Optionnel si un seul constructeur
public OrderService(ProductService productService) {
this.productService = productService;
}
}
@Service
public class NotificationService {
// Injection par champ (déconseillé mais fréquent)
@Autowired
private EmailService emailService;
// Injection par setter
@Autowired
public void setEmailService(EmailService emailService) {
this.emailService = emailService;
}
}
Préférez toujours l'injection par constructeur. Elle rend les dépendances explicites et facilite les tests.
@Qualifier
Résout les ambiguïtés quand plusieurs beans implémentent la même interface.
public interface NotificationSender {
void send(String message);
}
@Component("emailSender")
public class EmailNotification implements NotificationSender {
public void send(String message) { /* envoi email */ }
}
@Component("smsSender")
public class SmsNotification implements NotificationSender {
public void send(String message) { /* envoi SMS */ }
}
@Service
public class AlertService {
private final NotificationSender sender;
public AlertService(@Qualifier("emailSender") NotificationSender sender) {
this.sender = sender;
}
}
@Primary
Définit le bean par défaut quand plusieurs candidats existent.
@Primary
@Component
public class EmailNotification implements NotificationSender {
// Ce bean sera injecté par défaut
}
@Value
Injecte des valeurs depuis les fichiers de configuration.
@Service
public class AppConfig {
@Value("${app.name}")
private String appName;
@Value("${app.max-retry:3}") // Valeur par défaut = 3
private int maxRetry;
@Value("${server.port}")
private int port;
@Value("#{2 + 3}") // SpEL (Spring Expression Language)
private int calculated;
}
# application.yml
app:
name: MonApplication
max-retry: 5
server:
port: 8080
@Lazy
Retarde l'initialisation du bean jusqu'à sa première utilisation.
@Service
@Lazy
public class HeavyService {
public HeavyService() {
// Ce constructeur ne sera appelé que lorsque le bean est utilisé
}
}
4. Annotations de Configuration
@Configuration
Déclare une classe de configuration Spring (équivalent XML).
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
return mapper;
}
}
@Bean
Déclare un bean géré par le conteneur Spring. Utilisé dans les classes @Configuration.
@Configuration
public class SecurityConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public AuthenticationManager authManager(AuthenticationConfiguration config)
throws Exception {
return config.getAuthenticationManager();
}
}
@ConfigurationProperties
Lie un groupe de propriétés à un objet Java.
@Configuration
@ConfigurationProperties(prefix = "app.mail")
public class MailProperties {
private String host;
private int port;
private String username;
private String password;
// Getters et setters obligatoires
public String getHost() { return host; }
public void setHost(String host) { this.host = host; }
// ...
}
# application.yml
app:
mail:
host: smtp.gmail.com
port: 587
username: user@gmail.com
password: secret
@PropertySource
Charge un fichier de propriétés additionnel.
@Configuration
@PropertySource("classpath:custom-config.properties")
public class CustomConfig {
@Value("${custom.property}")
private String customProp;
}
@Import
Importe d'autres classes de configuration.
@Configuration
@Import({SecurityConfig.class, DatabaseConfig.class})
public class AppConfig {
}
5. Annotations de Scope et Lifecycle
@Scope
Définit la portée du bean.
@Component
@Scope("prototype") // Nouvelle instance à chaque injection
public class ShoppingCart {
private List<Item> items = new ArrayList<>();
}
| Scope | Description |
|---|---|
singleton | Une seule instance (par défaut) |
prototype | Nouvelle instance à chaque demande |
request | Une instance par requête HTTP |
session | Une instance par session HTTP |
application | Une instance par ServletContext |
@PostConstruct
Exécute une méthode après l'injection de toutes les dépendances.
@Service
public class CacheService {
private Map<String, Object> cache;
@PostConstruct
public void init() {
cache = new HashMap<>();
// Charger les données initiales
}
}
@PreDestroy
Exécute une méthode avant la destruction du bean.
@Service
public class ConnectionPool {
@PreDestroy
public void cleanup() {
// Fermer toutes les connexions
}
}
6. Annotations de Profil et Conditions
@Profile
Active un bean uniquement pour certains profils.
@Configuration
@Profile("dev")
public class DevDatabaseConfig {
@Bean
public DataSource dataSource() {
// H2 en mémoire pour le développement
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.build();
}
}
@Configuration
@Profile("prod")
public class ProdDatabaseConfig {
@Bean
public DataSource dataSource() {
// PostgreSQL pour la production
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl("jdbc:postgresql://localhost:5432/mydb");
return ds;
}
}
# Activer un profil
java -jar app.jar --spring.profiles.active=prod
@ConditionalOnProperty
Active un bean selon la valeur d'une propriété.
@Configuration
@ConditionalOnProperty(name = "app.feature.email", havingValue = "true")
public class EmailConfig {
@Bean
public EmailService emailService() {
return new SmtpEmailService();
}
}
@ConditionalOnClass
Active un bean si une classe est présente dans le classpath.
@Configuration
@ConditionalOnClass(name = "org.postgresql.Driver")
public class PostgresConfig {
// Configuré automatiquement si le driver PostgreSQL est disponible
}
@ConditionalOnMissingBean
Active un bean seulement si aucun autre bean du même type n'existe.
@Bean
@ConditionalOnMissingBean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
7. Annotations Lombok (Bonus)
Lombok génère du code automatiquement à la compilation.
@Data
Génère getters, setters, toString, equals, hashCode.
@Data
public class UserDto {
private Long id;
private String name;
private String email;
}
@Getter / @Setter
@Getter @Setter
public class Product {
private Long id;
private String name;
private BigDecimal price;
}
@NoArgsConstructor / @AllArgsConstructor / @RequiredArgsConstructor
@NoArgsConstructor
@AllArgsConstructor
public class Address {
private String street;
private String city;
private String zipCode;
}
@RequiredArgsConstructor // Constructeur pour les champs final
@Service
public class UserService {
private final UserRepository userRepository; // Injecté automatiquement
private final PasswordEncoder passwordEncoder;
}
@Builder
Implémente le pattern Builder.
@Builder
@Data
public class UserDto {
private Long id;
private String name;
private String email;
}
// Utilisation
UserDto user = UserDto.builder()
.id(1L)
.name("Jean")
.email("jean@example.com")
.build();
@Slf4j
Ajoute un logger SLF4J automatiquement.
@Slf4j
@Service
public class PaymentService {
public void processPayment(Payment payment) {
log.info("Traitement du paiement: {}", payment.getId());
log.debug("Montant: {}", payment.getAmount());
}
}
Résumé Rapide
| Annotation | Rôle |
|---|---|
@SpringBootApplication | Point d'entrée de l'application |
@Component | Bean générique |
@Service | Couche service (logique métier) |
@Repository | Couche données (accès BDD) |
@Controller | Contrôleur MVC |
@RestController | Contrôleur REST |
@Autowired | Injection de dépendance |
@Qualifier | Choix du bean à injecter |
@Value | Injection de valeur de config |
@Configuration | Classe de configuration |
@Bean | Déclaration manuelle de bean |
@ConfigurationProperties | Binding de propriétés |
@Profile | Activation par profil |
@PostConstruct | Initialisation après injection |
@PreDestroy | Nettoyage avant destruction |
➡️ Chapitre 2: Annotations Web et REST