1/86
Looks like no tags are added yet.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Which build tools can Spring Initializr use?
Definition: Maven or Gradle. Clarification: Maven uses pom.xml; Gradle uses build.gradle or build.gradle.kts.
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.
What does @SpringBootApplication combine?
Definition: @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. Clarification: It enables configuration, auto-configuration, and component scanning in a typical Boot app.
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.
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.
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.
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.
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.
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.
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.
What does 500 mean?
Definition: Internal Server Error. Clarification: Used for unexpected failures in server processing, unlike a client-side 4xx error.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
What does @Id do?
Definition: Identifies an entity's primary-key field. Clarification: The identifier distinguishes entity instances and is used in persistence operations.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.