Spring Boot IoC, Beans, Actuator, and REST Validation

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

1/106

encourage image

There's no tags or description

Looks like no tags are added yet.

107 Terms

1
New cards

What is Inversion of Control (IoC)?

A principle where Spring controls object creation, wiring, and lifecycle instead of application code. This is why application classes rely on the container rather than manually creating every collaborator with new. It improves loose coupling: application code declares what it needs instead of coordinating every dependency itself.

2
New cards

What is an IoC container?

The Spring component that creates, configures, wires, and manages beans. ApplicationContext is a common IoC container; it resolves and injects registered beans. It is responsible for resolving dependencies according to configuration and can apply lifecycle callbacks before beans are used.

3
New cards

What is Dependency Injection (DI)?

Supplying an object with dependencies from outside rather than constructing them inside the object. For example, an AccountController receives an AccountService through its constructor. This makes collaborators replaceable in unit tests and reduces tight coupling to concrete implementations.

4
New cards

How do IoC and DI relate?

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

5
New cards

What are the three DI types?

Constructor injection, setter injection, and field injection. Constructor injection passes dependencies at construction; setter injection calls setters; field injection writes fields. Constructor injection is usually preferred for required dependencies because the object cannot be created without them.

6
New cards

How do constructor and setter injection differ?

Constructor injection sets required dependencies at creation; setter injection supplies them afterward. Prefer a constructor for required dependencies; use setters when optional configuration is appropriate. Constructor injection also makes required dependencies explicit in the public API of a class.

7
New cards

Why is field injection less recommended?

It hides dependencies and complicates unit testing and immutability. Field injection makes dependencies less visible and often requires Spring or reflection for tests. Constructor injection usually makes the same class easier to instantiate in a plain unit test.

8
New cards

Which DI type is preferred for required dependencies?

Constructor injection: explicit dependencies, easy testing, and final fields. A single constructor is automatically used by Spring even without @Autowired. Marking injected fields final prevents accidental reassignment after construction.

9
New cards

What does @Autowired do?

Requests that Spring resolve and inject a matching bean. Often optional on single constructors; it may be placed on constructors, setters, or fields. Spring usually resolves candidates by type, and qualifiers can disambiguate multiple matches.

10
New cards

What is @Qualifier used for?

Selecting a specific bean when multiple candidates have the same type. For example, @Qualifier("emailSender") identifies which Sender bean should be injected. This is useful when an interface has several implementations, such as email and SMS notification services.

11
New cards

What does @Primary do?

Marks the preferred bean when several candidates match. If two implementations exist, @Primary supplies a default choice unless explicitly overridden. A qualifying injection point can still choose a different implementation.

12
New cards

What is BeanFactory compared with ApplicationContext?

BeanFactory is Spring's basic bean container abstraction. ApplicationContext extends that functionality with application events, message resolution, resource loading, and integration conveniences. In typical Spring Boot apps, ApplicationContext is the interface you encounter. Both belong to Spring's container architecture.

13
New cards

What is a Spring bean?

An object created, configured, and managed by the Spring IoC container. Spring can discover these objects using component scanning or register them through @Bean. The container may find the object through component scanning or a method annotated with @Bean.

14
New cards

What is component scanning?

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

15
New cards

What does @ComponentScan control?

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

16
New cards

Which annotations mark Spring components?

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

17
New cards

What are the basic bean lifecycle stages?

Instantiate → inject dependencies → initialize → use → destroy. Spring may execute awareness and post-processor callbacks around initialization; this is the basic interview sequence. Initialization callbacks such as @PostConstruct occur after dependency injection; cleanup callbacks such as @PreDestroy are scope-dependent.

18
New cards

What does @PostConstruct do?

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

19
New cards

What does @PreDestroy do?

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

20
New cards

What is singleton bean scope?

One bean instance per bean definition within one Spring container; the default. Singleton means container-scoped singleton, not necessarily one instance across the entire JVM. The same singleton bean is commonly shared by different controllers and services in one context.

21
New cards

What is prototype bean scope?

A new instance whenever that bean is requested from the container. Spring creates the prototype when requested but does not automatically run its destruction callbacks. Injecting a prototype into a singleton does not automatically make a fresh prototype for every method call.

22
New cards

What are the web bean scopes?

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

23
New cards

Request scope vs session scope?

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

24
New cards

What does @Bean do?

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

25
New cards

What does @Configuration do?

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

26
New cards

What is @Lazy?

@Lazy can defer initialization of a Spring bean rather than eagerly constructing it during application startup. It is useful for expensive or rarely used dependencies, but late initialization can also postpone discovering a configuration error.

27
New cards

How do @Component, @Service, and @Repository differ?

All register component-scanned Spring beans. @Component is generic, @Service signals business logic, and @Repository identifies persistence components. @Repository also participates in Spring's persistence exception translation; the annotations express architectural responsibilities.

28
New cards

What is Spring Initializr?

A tool that generates Spring Boot projects with build files, dependencies, and an entry point. At start.spring.io choose Java, Maven/Gradle, Boot version, group/artifact, and dependencies. The generated project can be opened directly in an IDE and run with Maven or Gradle.

29
New cards

Which build tools can Spring Initializr use?

Maven or Gradle. Maven uses pom.xml; Gradle uses build.gradle or build.gradle.kts.

30
New cards

What is a Spring Boot starter?

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

31
New cards

What does @SpringBootApplication combine?

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

32
New cards

What is Spring Boot Actuator?

A module exposing operational endpoints for health, metrics, and management. Add spring-boot-starter-actuator; secure sensitive endpoints before exposing them. The health endpoint is useful for liveness monitoring, while metrics help track application behavior in production.

33
New cards

What does /actuator/health show?

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

34
New cards

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

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

35
New cards

Why secure Actuator endpoints?

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

36
New cards

What is Spring Boot auto-configuration?

Spring Boot configures common application components based on classpath dependencies, properties, and existing beans. Adding Spring Web typically configures MVC infrastructure. You can customize or override defaults with your own beans and properties.

37
New cards

What is application.properties or application.yml used for?

These files externalize application settings such as server ports, database connectivity, logging levels, and custom configuration. For example, server.port=8081 changes the usual embedded server port.

38
New cards

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

1xx information; 2xx success; 3xx redirection; 4xx client error; 5xx server error. Remember the first digit: 1 information, 2 success, 3 redirect, 4 client issue, 5 server issue. A 4xx code typically indicates a request-side problem, while 5xx indicates a server-side failure.

39
New cards

What do 200, 201, and 204 mean?

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

40
New cards

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

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

41
New cards

What does 500 mean?

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

42
New cards

What do HTTP 301 and 302 mean?

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

43
New cards

How do you set a status code in a controller?

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

44
New cards

What does @Valid do on an endpoint parameter?

Triggers Bean Validation on the supplied object, such as @Valid @RequestBody UserDto dto. Constraint annotations belong on DTO fields; @Valid causes validation during argument binding. Spring can report a 400 Bad Request for invalid JSON request-body data in typical MVC configurations.

45
New cards

What happens when request-body validation fails?

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

46
New cards

What is @NotNull vs @NotEmpty vs @NotBlank?

@NotNull rejects null; @NotEmpty rejects null/empty; @NotBlank also rejects whitespace-only text. @NotBlank applies to Strings and rejects spaces; @NotEmpty also applies to collections. For example, a name consisting only of spaces fails @NotBlank but may pass a basic length check.

47
New cards

What does @Size do?

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

48
New cards

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

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

49
New cards

What does @ResponseStatus do?

@ResponseStatus declares an HTTP status on a controller handler or an exception class. Use @ResponseStatus(HttpStatus.CREATED) for 201, or ResponseEntity when a handler needs dynamic status, headers, and body.

50
New cards

How does @Validated differ from @Valid?

@Valid is the Jakarta Validation trigger. Spring's @Validated supports validation groups and Spring-specific validation integration. @Valid is common for @RequestBody DTOs; @Validated is useful when constraints differ across create and update operations.

51
New cards

What is @RestController?

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

52
New cards

How does @RestController differ from @Controller?

@RestController includes @ResponseBody; @Controller can return view names. Use @Controller for MVC pages; use @RestController primarily for API responses. It combines @Controller with @ResponseBody, so return values are written directly to HTTP responses.

53
New cards

What is @RequestMapping?

Defines a URL mapping and can constrain HTTP methods and other request conditions. A class-level @RequestMapping("/api/users") can prefix individual method mappings. You can map a shared path at class level and an HTTP-specific path at method level.

54
New cards

What are the five specialized HTTP mapping annotations?

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

55
New cards

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

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

56
New cards

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

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

57
New cards

What is Spring MVC?

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

58
New cards

What does DispatcherServlet do in Spring MVC?

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

59
New cards

What does ResponseEntity represent?

ResponseEntity represents a complete HTTP response, including status, headers, and optionally a response body. For a successful creation, ResponseEntity.status(HttpStatus.CREATED).body(resource) sends 201 with a body.

60
New cards

What is the difference between @RequestParam and @PathVariable?

@RequestParam binds a query parameter such as ?page=2; @PathVariable binds a URI template part such as /users/42. Use path variables to identify resources and query parameters for optional filters, paging, or search inputs.

61
New cards

What is ORM?

Object-Relational Mapping links Java objects and fields to relational tables and columns. A Customer class can correspond to a customers table, and each object to a row. Its primary advantage is reducing the repetitive code needed to map relational rows and columns into Java objects.

62
New cards

What is Hibernate?

A Java ORM framework that maps entities and performs persistence operations. Hibernate implements JPA and translates persistence operations into database interactions. It tracks entity state and translates many persistence operations into SQL for the configured database.

63
New cards

What are Hibernate benefits?

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

64
New cards

How do JPA and Hibernate relate?

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

65
New cards

What does @Entity do?

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

66
New cards

What does @Id do?

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

67
New cards

What does @GeneratedValue do?

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

68
New cards

How do Spring Data and Hibernate differ?

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

69
New cards

What is JpaRepository vs CrudRepository?

CrudRepository offers core CRUD; JpaRepository adds JPA-focused methods and paging/sorting inheritance. JpaRepository adds JPA conveniences such as flush/saveAndFlush and inherits pagination/sorting behavior. Using a standard persistence API allows application code to depend less directly on a specific ORM vendor.

70
New cards

What is a derived query method in Spring Data JPA?

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

71
New cards

What is the difference between @OneToMany and @ManyToOne?

@OneToMany models a collection of related entities; @ManyToOne models many entities referring to one parent entity. For example, one Customer has many Orders, while each Order references one Customer. Ownership affects foreign-key mapping.

72
New cards

How do LAZY and EAGER fetching differ?

LAZY fetching loads associated data when needed; EAGER fetching requests associated data with the owning entity. EAGER does not guarantee a single SQL query. Poor fetch choices can cause extra database work or N+1 queries.

73
New cards

What is the persistence context?

The JPA persistence context tracks managed entity instances and synchronizes changes with the database. Within a context, the EntityManager maintains entity identity and change tracking; flush synchronizes queued changes.

74
New cards

What is JPQL?

JPA-standard query language that queries entities and their properties. Write SELECT u FROM User u rather than querying the physical users table directly. For instance, SELECT c FROM Customer c queries the Customer entity rather than a physical table name.

75
New cards

What is HQL?

Hibernate Query Language: entity-based queries with Hibernate-specific features. Similar to JPQL but may support additional Hibernate-specific query features. HQL and JPQL are similar, but HQL provides extensions specific to Hibernate.

76
New cards

What is native SQL?

Direct SQL targeting physical database tables and columns. Useful for vendor-specific SQL or complex database queries; portability may be lower. Because it references real database tables, schema and vendor changes can affect portability.

77
New cards

What is the Criteria API?

A Java API for constructing type-aware, dynamic entity queries programmatically. CriteriaBuilder and CriteriaQuery are especially useful for combining optional filters. CriteriaBuilder combines predicates programmatically, which is useful for filters supplied at runtime.

78
New cards

When should you use native SQL rather than JPQL?

Use native SQL when you need database-specific features, specialized SQL, or queries impractical in JPQL. The trade-off is reduced portability and a tighter coupling to the underlying database schema.

79
New cards

What does @Transactional do?

Defines a Spring-managed transaction boundary for commit and rollback. On success, Spring commits; by default unchecked exceptions trigger rollback in proxied transactional calls. It is commonly placed around service-layer operations because one business action may span multiple repository calls.

80
New cards

What does ACID stand for?

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

81
New cards

What is the default @Transactional propagation?

REQUIRED: join an existing transaction or create one if none exists. If a calling method already has a transaction, the called method usually participates in it. This typically belongs on a service method that coordinates several related database updates.

82
New cards

How does REQUIRES_NEW differ from REQUIRED?

REQUIRES_NEW suspends an existing transaction and starts an independent one. The outer transaction is suspended while the new transaction executes independently. The independent transaction can commit even if the surrounding transaction later rolls back.

83
New cards

What does NESTED propagation do?

Creates a nested transaction using a savepoint when supported. The nested work can roll back to its savepoint without always aborting the outer transaction. Savepoint behavior depends on the configured transaction manager and underlying database support.

84
New cards

What do SUPPORTS and MANDATORY mean?

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

85
New cards

What do NOT_SUPPORTED and NEVER mean?

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

86
New cards

When does @Transactional roll back by default?

Normally on unchecked RuntimeException and Error, not ordinary checked exceptions. Use rollbackFor to include checked exceptions when required by business rules. This typically belongs on a service method that coordinates several related database updates.

87
New cards

What is transaction isolation?

Rules governing how concurrent transactions see each other's database changes. Levels such as READ_COMMITTED and SERIALIZABLE control visibility and concurrency behavior. For example, READ_COMMITTED prevents reading another transaction's uncommitted changes.

88
New cards

Why is @Transactional often put on service methods?

Service methods define business units of work that may involve several repository operations and must succeed together. A transfer service can withdraw and deposit inside one transaction, avoiding a committed half-transfer after failure.

89
New cards

What is transaction self-invocation?

When a Spring bean calls its own @Transactional method directly, the call commonly bypasses proxy interception. In default proxy-based transaction management, the annotation may not apply on that internal call; use an appropriate bean boundary.

90
New cards

What is Spring Security?

A framework for authentication and authorization of Spring applications. Security rules typically apply through SecurityFilterChain before a request reaches a controller. Requests are commonly checked by a SecurityFilterChain before the controller handles them.

91
New cards

What is authentication vs authorization?

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

92
New cards

What is SecurityConfig?

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

93
New cards

What is CORS?

Cross-Origin Resource Sharing: browser rules for accessing responses from another origin. Example: an Angular app on port 4200 calling an API on port 8080 is cross-origin. For example, localhost:4200 and localhost:8080 are different origins because their ports differ.

94
New cards

What is UserDetailsService?

A Spring Security interface that loads user information through loadUserByUsername(). Its main method is loadUserByUsername(); it supplies user details for authentication. Its loadUserByUsername method returns information used by authentication infrastructure.

95
New cards

What is UserDetailsManager?

Extends UserDetailsService with operations to create, update, and delete users. Implementations can also check whether a user exists and update passwords. It adds account creation, update, deletion, and password-management capabilities.

96
New cards

What is RBAC?

Role-Based Access Control: permissions granted through roles such as USER or ADMIN. A USER role might read records while ADMIN can manage accounts; RBAC is authorization. For example, an ADMIN may delete user records while a USER can only read their own profile.

97
New cards

How can Spring Security restrict an endpoint to admins?

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

98
New cards

What is SecurityFilterChain?

SecurityFilterChain is a Spring Security configuration bean specifying request protection, authentication mechanisms, and authorization rules. For example, permit /public/** but require authentication elsewhere; filters process requests before controllers.

99
New cards

What does @CrossOrigin do?

@CrossOrigin configures allowed cross-origin browser access for a controller or request handler. It can authorize a frontend origin such as http://localhost:4200, but CORS is not a replacement for authorization.

100
New cards

What is PasswordEncoder used for?

PasswordEncoder hashes passwords for secure storage and verifies submitted passwords against stored hashes. Use an adaptive password hash such as BCrypt, not plaintext or reversible encryption.