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>
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
Przykład przez konstruktor:
@Service public class UserService { private final UserRepository repository; public UserService(UserRepository repository) { this.repository = repository; } }
@Component, @Service, @Repository, @Controller)@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(); } }
<beans> <bean id="userService" class="com.example.UserService"/> </beans>
@Component, @Service, …) i Spring sam je wykrywa przez component scanning @Configuration public class AppConfig { @Bean public UserService userService() { return new UserService(userRepository()); } @Bean public UserRepository userRepository() { return new UserRepository(); } }
Spring Boot to framework oparty na Spring, który upraszcza i przyspiesza tworzenie aplikacji Spring.
Spring Boot w IntelliJ IDEA File > New > Project > Spring BootStruktura katalogów:
src/main/java - kod źródłowy aplikacjisrc/main/resources - zasoby (konfiguracja, pliki statyczne)src/test/java - testypom.xml lub build.gradle - konfiguracja budowania
Plik application.properties lub application.yml - konfiguracja aplikacji.
Główna klasa aplikacji:
@SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Adnotacja @SpringBootApplication odpowiada za:
@Configuration - definiuje klasę jako źródło konfiguracji@EnableAutoConfiguration - włącza automatyczną konfigurację@ComponentScan - szuka komponentów w bieżącym pakiecie@Controller lub @RestController@Controller - metody zwracają nazwy widoków @RestController - metody zwracają dane (JSON)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:
@Controller - oznacza klasę jako kontroler@RequestMapping - mapuje URL@GetMapping, @PostMapping - mapuje konkretne metody HTTP@RestController @RequestMapping("/api/users") public class UserRestController { @GetMapping public List<User> getAllUsers() { return userService.findAll(); } @GetMapping("/{id}") public User getUserById(@PathVariable Long id) { return userService.findById(id); } @PostMapping public User createUser(@RequestBody User user) { return userService.save(user); } @DeleteMapping("/{id}") public void deleteUser(@PathVariable Long id) { userService.delete(id); } }
@RestController - kombinacja @Controller i @ResponseBody, zwraca JSON.
@RequestMapping - mapuje URL i metody HTTP.
@GetMapping, @PostMapping, @PutMapping, @DeleteMapping - skróty dla konkretnych metod HTTP.
@PathVariable - parametry w ścieżce URL (np. /users/{id}).
@RequestParam - parametry zapytania (np. ?page=1&size=10).
@RequestBody - mapowanie body żądania na obiekt Java.
@ResponseBody - konwersja obiektu na JSON.
Spring Boot automatycznie serwuje pliki statyczne z folderów:
src/main/resources/staticsrc/main/resources/publicsrc/main/resources/resourcessrc/main/resources/META-INF/resourcesPliki (HTML, CSS, JavaScript, obrazy) są dostępne bezpośrednio w aplikacji.
Globalna obsługa wyjątków:
@ControllerAdvice 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"); } }
@ControllerAdvice - klasa globalnej obsługi wyjątków.
@ExceptionHandler - metoda obsługująca konkretny typ wyjątku.
application.properties.application.properties:spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=password spring.jpa.hibernate.ddl-auto=update spring.jpa.show-sql=true
Definicja encji:
@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; }
Definicja repozytorium:
@Repository public interface UserRepository extends JpaRepository<User, Long> { User findByEmail(String email); }
save() - tworzenie i aktualizacjafindAll() - pobranie wszystkichfindById() - pobranie po IDdelete() - usunięcieSpring Security - framework do zabezpieczeń i autoryzacji.
@Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/public/**") .permitAll() .anyRequest() .authenticated()) .formLogin(); return http.build(); } }
@PreAuthorize - weryfikacja uprawnień na metodzie@Secured - alternatywa dla @PreAuthorize@RestController @RequestMapping("/api/admin") public class AdminController { @DeleteMapping("/users/{id}") @PreAuthorize("hasRole('ADMIN')") public void deleteUser(@PathVariable Long id) { userService.delete(id); } }
Adnotacja @PreAuthorize sprawdza, czy użytkownik ma rolę ADMIN.