Spring Boot & MVC: IoC, Beans, Validation, HTTP

0.0(0)
Studied by 0 people
call kaiCall Kai
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
GameKnowt Play
Card Sorting

1/86

encourage image

There's no tags or description

Looks like no tags are added yet.

87 Terms

1
New cards

What is Inversion of Control (IoC)?

Definition: A principle where Spring controls object creation, wiring, and lifecycle instead of application code. Clarification: This is why application classes rely on the container rather than manually creating every collaborator with new.

2
New cards

What is an IoC container?

Definition: The Spring component that creates, configures, wires, and manages beans. Clarification: ApplicationContext is a common IoC container; it resolves and injects registered beans.

3
New cards

What is Dependency Injection (DI)?

Definition: Supplying an object with dependencies from outside rather than constructing them inside the object. Clarification: For example, an AccountController receives an AccountService through its constructor.

4
New cards

How do IoC and DI relate?

Definition: IoC is the principle; DI is a common way Spring implements it. Clarification: IoC describes who controls creation; DI describes how collaborators are supplied.

5
New cards

What are the three DI types?

Definition: Constructor injection, setter injection, and field injection. Clarification: Constructor injection passes dependencies at construction; setter injection calls setters; field injection writes fields.

6
New cards

How do constructor and setter injection differ?

Definition: Constructor injection sets required dependencies at creation; setter injection supplies them afterward. Clarification: Prefer a constructor for required dependencies; use setters when optional configuration is appropriate.

7
New cards

Why is field injection less recommended?

Definition: It hides dependencies and complicates unit testing and immutability. Clarification: Field injection makes dependencies less visible and often requires Spring or reflection for tests.

8
New cards

Which DI type is preferred for required dependencies?

Definition: Constructor injection: explicit dependencies, easy testing, and final fields. Clarification: A single constructor is automatically used by Spring even without @Autowired.

9
New cards

What does @Autowired do?

Definition: Requests that Spring resolve and inject a matching bean. Clarification: Often optional on single constructors; it may be placed on constructors, setters, or fields.

10
New cards

What is @Qualifier used for?

Definition: Selecting a specific bean when multiple candidates have the same type. Clarification: For example, @Qualifier("emailSender") identifies which Sender bean should be injected.

11
New cards

What does @Primary do?

Definition: Marks the preferred bean when several candidates match. Clarification: If two implementations exist, @Primary supplies a default choice unless explicitly overridden.

12
New cards

What is a Spring bean?

Definition: An object created, configured, and managed by the Spring IoC container. Clarification: Spring can discover these objects using component scanning or register them through @Bean.

13
New cards

What is component scanning?

Definition: Spring discovers annotated components in selected packages and registers them as beans. Clarification: Scanning typically begins at the application package and includes its subpackages.

14
New cards

What does @ComponentScan control?

Definition: The packages Spring scans to find annotated classes and register beans. Clarification: @ComponentScan can specify base packages to include classes outside the default search area.

15
New cards

Which annotations mark Spring components?

Definition: @Component, @Service, @Repository, and @Controller; @RestController is also a component. Clarification: @Service indicates business logic, @Repository persistence, and @Controller web request handling.

16
New cards

What are the basic bean lifecycle stages?

Definition: Instantiate → inject dependencies → initialize → use → destroy. Clarification: Spring may execute awareness and post-processor callbacks around initialization; this is the basic interview sequence.

17
New cards

What does @PostConstruct do?

Definition: Runs an initialization method after dependencies are injected. Clarification: Use it for setup that requires injected collaborators; it runs before normal bean use.

18
New cards

What does @PreDestroy do?

Definition: Runs cleanup before a managed bean is destroyed; not automatically for prototype beans. Clarification: Typical cleanup closes resources for eligible scopes; Spring does not destroy prototypes automatically.

19
New cards

What is singleton bean scope?

Definition: One bean instance per bean definition within one Spring container; the default. Clarification: Singleton means container-scoped singleton, not necessarily one instance across the entire JVM.

20
New cards

What is prototype bean scope?

Definition: A new instance whenever that bean is requested from the container. Clarification: Spring creates the prototype when requested but does not automatically run its destruction callbacks.

21
New cards

What are the web bean scopes?

Definition: Request, session, application, and WebSocket scopes. Clarification: Request and session are web-aware; application scope belongs to ServletContext and WebSocket to a socket session.

22
New cards

Request scope vs session scope?

Definition: Request creates one bean per HTTP request; session uses one per HTTP session. Clarification: A request-scoped object lasts one request; a session-scoped object persists across requests in a session.

23
New cards

What does @Bean do?

Definition: Registers the return value of a configuration method as a Spring-managed bean. Clarification: Useful for registering third-party objects you cannot annotate with @Component.

24
New cards

What does @Configuration do?

Definition: Marks a class containing bean definitions and application configuration. Clarification: Typically pairs with @Bean methods; Spring processes it as a source of bean definitions.

25
New cards

What is Spring Initializr?

Definition: A tool that generates Spring Boot projects with build files, dependencies, and an entry point. Clarification: At start.spring.io choose Java, Maven/Gradle, Boot version, group/artifact, and dependencies.

26
New cards

Which build tools can Spring Initializr use?

Definition: Maven or Gradle. Clarification: Maven uses pom.xml; Gradle uses build.gradle or build.gradle.kts.

27
New cards

What is a Spring Boot starter?

Definition: A curated dependency bundle for a feature such as web, JPA, or security. Clarification: spring-boot-starter-web, -data-jpa, and -security simplify dependency setup.

28
New cards

What does @SpringBootApplication combine?

Definition: @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. Clarification: It enables configuration, auto-configuration, and component scanning in a typical Boot app.

29
New cards

What is Spring Boot Actuator?

Definition: A module exposing operational endpoints for health, metrics, and management. Clarification: Add spring-boot-starter-actuator; secure sensitive endpoints before exposing them.

30
New cards

What does /actuator/health show?

Definition: Application health status, commonly UP or DOWN. Clarification: Health indicators can reflect application and dependency conditions; details depend on configuration.

31
New cards

What do /actuator/info and /actuator/metrics do?

Definition: Info shows configured app information; metrics exposes measurements. Clarification: Only selected endpoints are exposed over HTTP by default; exposure settings can be changed.

32
New cards

Why secure Actuator endpoints?

Definition: Some endpoints reveal sensitive application and operational details. Clarification: Metrics, environment, and bean details can expose internal structure if unsecured.

33
New cards

What do HTTP status categories 1xx-5xx mean?

Definition: 1xx information; 2xx success; 3xx redirection; 4xx client error; 5xx server error. Clarification: Remember the first digit: 1 information, 2 success, 3 redirect, 4 client issue, 5 server issue.

34
New cards

What do 200, 201, and 204 mean?

Definition: 200 OK; 201 Created; 204 No Content. Clarification: 201 is common after creation; 204 represents success without a response body.

35
New cards

What do 400, 401, 403, and 404 mean?

Definition: 400 Bad Request; 401 Unauthorized; 403 Forbidden; 404 Not Found. Clarification: 401 concerns authentication credentials; 403 means access is forbidden.

36
New cards

What does 500 mean?

Definition: Internal Server Error. Clarification: Used for unexpected failures in server processing, unlike a client-side 4xx error.

37
New cards

What do HTTP 301 and 302 mean?

Definition: 301 Moved Permanently; 302 Found (temporary redirection). Clarification: Both redirect clients; 301 is permanent and 302 is traditionally temporary.

38
New cards

How do you set a status code in a controller?

Definition: Use ResponseEntity.status(HttpStatus.CREATED).body(value), or @ResponseStatus. Clarification: ResponseEntity controls both status and body; @ResponseStatus can declare a fixed status.

39
New cards

What does @Valid do on an endpoint parameter?

Definition: Triggers Bean Validation on the supplied object, such as @Valid @RequestBody UserDto dto. Clarification: Constraint annotations belong on DTO fields; @Valid causes validation during argument binding.

40
New cards

What happens when request-body validation fails?

Definition: Spring MVC typically returns 400 Bad Request for invalid @Valid request bodies. Clarification: A binding or validation exception may be handled centrally to customize the error response.

41
New cards

What is @NotNull vs @NotEmpty vs @NotBlank?

Definition: @NotNull rejects null; @NotEmpty rejects null/empty; @NotBlank also rejects whitespace-only text. Clarification: @NotBlank applies to Strings and rejects spaces; @NotEmpty also applies to collections.

42
New cards

What does @Size do?

Definition: Sets minimum and maximum length or size for supported values. Clarification: Example: @Size(min=3,max=30) on a username; it does not replace @NotNull.

43
New cards

What do @Email, @Min, @Max, and @Pattern do?

Definition: Validate email format, numeric bounds, and regex pattern, respectively. Clarification: Example: @Email on an email field and @Pattern on a formatted identifier.

44
New cards

What is @RestController?

Definition: A controller whose handler return values are written directly to HTTP response bodies, often as JSON. Clarification: It combines @Controller and @ResponseBody; Jackson commonly serializes returned objects to JSON.

45
New cards

How does @RestController differ from @Controller?

Definition: @RestController includes @ResponseBody; @Controller can return view names. Clarification: Use @Controller for MVC pages; use @RestController primarily for API responses.

46
New cards

What is @RequestMapping?

Definition: Defines a URL mapping and can constrain HTTP methods and other request conditions. Clarification: A class-level @RequestMapping("/api/users") can prefix individual method mappings.

47
New cards

What are the five specialized HTTP mapping annotations?

Definition: @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping. Clarification: GET reads, POST submits, PUT replaces, PATCH modifies part, DELETE removes.

48
New cards

What are GET, POST, PUT, PATCH, DELETE commonly used for?

Definition: Retrieve, create, replace, partially update, and delete resources. Clarification: These represent common REST conventions; the server defines the exact endpoint behavior.

49
New cards

What do @PathVariable, @RequestParam, @RequestBody do?

Definition: Bind URL path parts, query parameters, and request body data to method arguments. Clarification: Example: /users/{id} uses @PathVariable; ?active=true uses @RequestParam.

50
New cards

What is Spring MVC?

Definition: Spring's web framework for HTTP request handling using Model-View-Controller and DispatcherServlet. Clarification: Its Model carries data, View renders a presentation, and Controller processes requests.

51
New cards

What does DispatcherServlet do in Spring MVC?

Definition: Acts as the front controller, dispatching HTTP requests to handlers. Clarification: It receives requests and works with handler mappings and adapters to invoke controllers.

52
New cards

What is ORM?

Definition: Object-Relational Mapping links Java objects and fields to relational tables and columns. Clarification: A Customer class can correspond to a customers table, and each object to a row.

53
New cards

What is Hibernate?

Definition: A Java ORM framework that maps entities and performs persistence operations. Clarification: Hibernate implements JPA and translates persistence operations into database interactions.

54
New cards

What are Hibernate benefits?

Definition: Less JDBC boilerplate, object mapping, caching, and database dialect support. Clarification: It also manages entity state and reduces repetitive mapping between Java types and SQL rows.

55
New cards

How do JPA and Hibernate relate?

Definition: JPA is a persistence specification; Hibernate is an implementation of it. Clarification: Code written to JPA interfaces can often work with Hibernate or another JPA provider.

56
New cards

What does @Entity do?

Definition: Marks a class as a persistent entity mapped to a database table. Clarification: Combine with @Id for an entity key; @Table can customize the database table name.

57
New cards

What does @Id do?

Definition: Identifies an entity's primary-key field. Clarification: The identifier distinguishes entity instances and is used in persistence operations.

58
New cards

What does @GeneratedValue do?

Definition: Configures how an entity primary-key value is generated. Clarification: Strategies include IDENTITY and SEQUENCE, depending on database support and configuration.

59
New cards

How do Spring Data and Hibernate differ?

Definition: Spring Data offers repository abstractions; Hibernate performs ORM and persistence. Clarification: Spring Data JPA often delegates persistence work to JPA/Hibernate under the repository interface.

60
New cards

What is JpaRepository vs CrudRepository?

Definition: CrudRepository offers core CRUD; JpaRepository adds JPA-focused methods and paging/sorting inheritance. Clarification: JpaRepository adds JPA conveniences such as flush/saveAndFlush and inherits pagination/sorting behavior.

61
New cards

What is a derived query method in Spring Data JPA?

Definition: A repository method such as findByEmail() whose name defines a query. Clarification: Spring Data parses method names, e.g. findByEmail(String email), to build matching queries.

62
New cards

What is JPQL?

Definition: JPA-standard query language that queries entities and their properties. Clarification: Write SELECT u FROM User u rather than querying the physical users table directly.

63
New cards

What is HQL?

Definition: Hibernate Query Language: entity-based queries with Hibernate-specific features. Clarification: Similar to JPQL but may support additional Hibernate-specific query features.

64
New cards

What is native SQL?

Definition: Direct SQL targeting physical database tables and columns. Clarification: Useful for vendor-specific SQL or complex database queries; portability may be lower.

65
New cards

What is the Criteria API?

Definition: A Java API for constructing type-aware, dynamic entity queries programmatically. Clarification: CriteriaBuilder and CriteriaQuery are especially useful for combining optional filters.

66
New cards

What does @Transactional do?

Definition: Defines a Spring-managed transaction boundary for commit and rollback. Clarification: On success, Spring commits; by default unchecked exceptions trigger rollback in proxied transactional calls.

67
New cards

What does ACID stand for?

Definition: Atomicity, Consistency, Isolation, Durability: key transaction properties. Clarification: Atomicity is all-or-nothing; consistency keeps rules; isolation separates work; durability preserves commits.

68
New cards

What is the default @Transactional propagation?

Definition: REQUIRED: join an existing transaction or create one if none exists. Clarification: If a calling method already has a transaction, the called method usually participates in it.

69
New cards

How does REQUIRES_NEW differ from REQUIRED?

Definition: REQUIRES_NEW suspends an existing transaction and starts an independent one. Clarification: The outer transaction is suspended while the new transaction executes independently.

70
New cards

What does NESTED propagation do?

Definition: Creates a nested transaction using a savepoint when supported. Clarification: The nested work can roll back to its savepoint without always aborting the outer transaction.

71
New cards

What do SUPPORTS and MANDATORY mean?

Definition: SUPPORTS uses a transaction if present; MANDATORY fails if none exists. Clarification: MANDATORY throws an exception without a transaction; SUPPORTS can execute without one.

72
New cards

What do NOT_SUPPORTED and NEVER mean?

Definition: NOT_SUPPORTED runs without a transaction; NEVER fails if one exists. Clarification: NOT_SUPPORTED suspends a current transaction; NEVER raises an error if one exists.

73
New cards

When does @Transactional roll back by default?

Definition: Normally on unchecked RuntimeException and Error, not ordinary checked exceptions. Clarification: Use rollbackFor to include checked exceptions when required by business rules.

74
New cards

What is transaction isolation?

Definition: Rules governing how concurrent transactions see each other's database changes. Clarification: Levels such as READ_COMMITTED and SERIALIZABLE control visibility and concurrency behavior.

75
New cards

What is Spring Security?

Definition: A framework for authentication and authorization of Spring applications. Clarification: Security rules typically apply through SecurityFilterChain before a request reaches a controller.

76
New cards

What is authentication vs authorization?

Definition: Authentication verifies identity; authorization determines allowed actions. Clarification: Logging in identifies a user; checking whether they can access /admin is authorization.

77
New cards

What is SecurityConfig?

Definition: A conventional configuration class defining security beans and access rules, such as SecurityFilterChain. Clarification: It is a conventional class name, commonly annotated @Configuration, not a mandatory Spring annotation.

78
New cards

What is CORS?

Definition: Cross-Origin Resource Sharing: browser rules for accessing responses from another origin. Clarification: Example: an Angular app on port 4200 calling an API on port 8080 is cross-origin.

79
New cards

What is UserDetailsService?

Definition: A Spring Security interface that loads user information through loadUserByUsername(). Clarification: Its main method is loadUserByUsername(); it supplies user details for authentication.

80
New cards

What is UserDetailsManager?

Definition: Extends UserDetailsService with operations to create, update, and delete users. Clarification: Implementations can also check whether a user exists and update passwords.

81
New cards

What is RBAC?

Definition: Role-Based Access Control: permissions granted through roles such as USER or ADMIN. Clarification: A USER role might read records while ADMIN can manage accounts; RBAC is authorization.

82
New cards

How can Spring Security restrict an endpoint to admins?

Definition: Use an authorization rule such as hasRole("ADMIN") for the endpoint. Clarification: Configure request authorization or method security; users must have the required authority.

83
New cards

What is @RestControllerAdvice?

Definition: Global advice for REST controllers, including centralized exception handling and response bodies. Clarification: Centralizes handling across controllers so every endpoint need not repeat try/catch logic.

84
New cards

How does @ControllerAdvice differ from @RestControllerAdvice?

Definition: @RestControllerAdvice includes @ResponseBody, suitable for REST error responses. Clarification: Use @RestControllerAdvice for response bodies; @ControllerAdvice can also support MVC views.

85
New cards

What is @ExceptionHandler?

Definition: Marks a method to handle specified exception types thrown during request processing. Clarification: The handler can map a specific exception to an error message and HTTP status.

86
New cards

How do @RestControllerAdvice and @ExceptionHandler work together?

Definition: The advice class applies globally; @ExceptionHandler chooses exceptions and returns a suitable HTTP response. Clarification: Example: catch ResourceNotFoundException globally and return 404 Not Found.

87
New cards

What status might a missing resource exception return?

Definition: 404 Not Found, often set with ResponseEntity or @ResponseStatus in an exception handler. Clarification: The handler may use ResponseEntity.status(HttpStatus.NOT_FOUND) with an error body.