Saltar al contenido principal

Guía de Inicio Rápido

Esta guía le permite iniciar su proyecto final rápidamente.


1. Creación del Proyecto​

Con Spring Initializr​

  1. Ir a https://start.spring.io

  2. Configurar:

    • Project: Maven
    • Language: Java
    • Spring Boot: 3.2.x
    • Group: com.example
    • Artifact: proyecto-final
    • Packaging: Jar
    • Java: 21
  3. Agregar las dependencias:

    • Spring Web
    • Spring Data JPA
    • Spring Security
    • Validation
    • Lombok
    • PostgreSQL Driver
    • H2 Database (dev)
  4. Descargar y extraer

Estructura Inicial​

projet-final/
├── src/main/java/com/example/projet/
│ └── ProjetFinalApplication.java
├── src/main/resources/
│ └── application.properties
├── src/test/java/
└── pom.xml

2. Configuración Básica​

pom.xml - Dependencias Esenciales​

<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. Esqueleto Básico​

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. Comandos Útiles​

Ejecución​

# Desarrollo
./mvnw spring-boot:run

# Con perfil
./mvnw spring-boot:run -Dspring-boot.run.profiles=dev

# Build
./mvnw clean package -DskipTests

# Ejecutar JAR
java -jar target/projet-final-0.0.1-SNAPSHOT.jar

Pruebas​

# Todas las pruebas
./mvnw test

# Pruebas específicas
./mvnw test -Dtest=UserServiceTest

# Con cobertura
./mvnw test jacoco:report

Base de Datos​

# H2 Console
http://localhost:8080/h2-console
# JDBC URL: jdbc:h2:mem:devdb
# Username: sa
# Password: (vacío)

5. Checklist de Inicio​

  • Proyecto creado con Spring Initializr
  • Dependencias agregadas en pom.xml
  • application.yml configurado
  • Entidad User creada
  • Repositorio User creado
  • Seguridad configurada
  • Endpoint /api/auth/register funciona
  • Endpoint /api/auth/login funciona
  • Pruebas básicas pasan

6. Próximos Pasos​

  1. Agregar las entidades específicas de su proyecto
  2. Implementar los servicios de negocio
  3. Crear los controladores REST
  4. Agregar la validación
  5. Implementar las pruebas
  6. Documentar la API

Volver al Proyecto Final