Spis treści

REVEAL theme=simple&disableLayout=0&transition=none&controls=1&show_progress_bar=1&build_all_lists=0&show_image_borders=0&horizontal_slide_level=2&enlarge_vertical_slide_headers=0&show_slide_details=1&open_in_new_window=1&size=1024×768

<html> <style type=„text/css”> p { text-align: left;} .reveal { font-size: 30px; } .reveal section { width: 96%; margin: 0 auto; } .reveal .slides { width: 60% !important; } .reveal ul, .reveal ol { margin-left: 1.5em; } .reveal pre code {

height: 100%;
max-height: 100%;
box-sizing: border-box; }

</style> </html>

Co to jest Spring Framework

Spring to zaawansowana platforma do tworzenia aplikacji w Javie. Składa się z wielu modułów wspierających różne aspekty tworzenia aplikacji.

Kluczowym elementem jest kontener IoC (Inversion of Control) udostępniający mechanizm wstrzykiwania zależności (Dependency Injection), co przyspiesza i upraszcza składanie aplikacji.

Spring to „framework frameworków„ - jeden z najpopularniejszych i najbardziej wszechstronnych frameworków w ekosystemie Java.

Strona projektu: spring.io

Spring w IntelliJ IDEA: Spring support in IntelliJ IDEA

Najważniejsze cechy Spring

Aspect-Oriented Programming (AOP)

Inversion of Control (IoC)


IoC - Inversion of Control

Dependency Injection

Przykład przez konstruktor:

@Service
public class UserService {
    private final UserRepository repository;
 
    public UserService(UserRepository repository) {
        this.repository = repository;
    }
}

Spring - moduły

Podstawowe moduły Spring

Zalety korzystania ze Spring

Najważniejsze elementy Spring

Cykl życia beanów

Cykl życia beanów

Adnotacje Spring

@Component - oznacza klasę jako komponent zarządzany przez Spring.

@Service - specjalizacja @Component, oznacza klasę jako usługę biznesową.

@Repository - specjalizacja @Component, oznacza klasę do dostępu do danych.

@Autowired - wstrzykuje zależność (może być na polu, setterze lub konstruktorze).

@Configuration - oznacza klasę, która zawiera definicje beanów.

@Bean - oznacza metodę, która zwraca bean zarządzany przez Spring.

@Configuration
public class AppConfig {  
    @Bean
    public UserService userService() {
        return new UserService(userRepository());
    }
 
    @Bean
    public UserRepository userRepository() {
        return new UserRepository();
    }
}

Konfiguracja Spring

Co to jest Spring Boot

Spring Boot to framework oparty na Spring, który upraszcza i przyspiesza tworzenie aplikacji Spring.

Instalacja i konfiguracja

Struktura projektu Spring Boot

Struktura projektu Spring Boot

Struktura katalogów:

Plik application.properties lub application.yml - konfiguracja aplikacji.

Tworzenie i uruchamianie aplikacji

Główna klasa aplikacji:

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

Adnotacja @SpringBootApplication odpowiada za:

Typowa struktura aplikacji

Warstwy architektoniczne w Spring Boot

Warstwy architektoniczne

Spring Boot MVC

Obsługa plików statycznych

Spring Boot automatycznie serwuje pliki statyczne z folderów:

Pliki (HTML, CSS, JavaScript, obrazy) są dostępne bezpośrednio w aplikacji.

Mapowanie nazw widoków na szablony:

Kontrolery w Spring MVC

Przykład prostego kontrolera:

@Controller
@RequestMapping("/users")
public class UserController {
 
    @GetMapping
    public String listUsers(Model model) {
        model.addAttribute("users", userService.findAll());
        return "users/list";
    }
 
    @PostMapping
    public String createUser(@ModelAttribute User user) {
        userService.save(user);
        return "redirect:/users";
    }
}

Adnotacje:

Przykład REST API

@RestController
@RequestMapping("/api/")
public class UserRestController {
 
    @GetMapping
    public List<User> getAllUsers() {
        return userService.findAll();
    }
 
    @GetMapping("/users/{id}")
    public User getUserById(@PathVariable Long id) {
        return userService.findById(id);
    }
 
    @PostMapping("/users")
    public User createUser(@RequestBody User user) {
        return userService.save(user);
    }
 
    @DeleteMapping("/users/{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.delete(id);
    }
}

Adnotacje dla REST API

Services

interface UserService {
    List<User> findAll();
    User findById(Long id);
    User save(User user);
    void delete(Long id);
}
 
@Service
public class UserServiceImpl implements UserService {  
 
    @Autowired
    private final UserRepository repository;
 
    public List<User> findAll() {
        return repository.findAll();
    }
 
  /* ... */   
}

Łączenie z bazą danych

Przykład:

spring.datasource.url=jdbc:mysql://localhost:3306/mydb
spring.datasource.username=root
spring.datasource.password=password

Spring Data JPA

Aplikacja CRUD

Repozytoria

Definicja repozytorium:

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
    User findByEmail(String email);
}

Konfiguracja połączenia z bazą danych

Ustawienia w application.properties lub application.yml:

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true

Encje

@Entity
@Table(name = "users")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
 
    @Column(nullable = false, unique = true)
    private String email;
 
    @Column(nullable = false)
    private String name;
}

ResponseEntity

@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
    User user = userService.findById(id);
    if (user != null) {
        return ResponseEntity.ok(user);
    } else {
        return ResponseEntity.notFound().build();
    }
}

ResponseStatus

Jest on zamieniany na odpowiednią odpowiedź HTTP przez Spring.

@ResponseStatus(HttpStatus.NO_CONTENT)
@DeleteMapping("/users/{id}")
public ResponseEntity<Void> deleteUser(@PathVariable Integer id) {
    User user = userService.findById(id);
    if (user == null) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found: " + id);
    }
    userService.deleteUser(id);
}

Obsługa błędów w REST API

@RestControllerAdvice
public class GlobalExceptionHandler {
 
    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(
            ResourceNotFoundException ex) {
        return ResponseEntity
            .status(HttpStatus.NOT_FOUND)
            .body(ex.getMessage());
    }
 
    @ExceptionHandler(Exception.class)
    public ResponseEntity<String> handleGeneral(Exception ex) {
        return ResponseEntity
            .status(HttpStatus.INTERNAL_SERVER_ERROR)
            .body("Błąd serwera");
    }
}

Dokumentacja