1/106
Looks like no tags are added yet.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Which build tools can Spring Initializr use?
Maven or Gradle. Maven uses pom.xml; Gradle uses build.gradle or build.gradle.kts.
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.
What does @SpringBootApplication combine?
@SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. It enables configuration, auto-configuration, and component scanning in a typical Boot app.
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.
What does /actuator/health show?
Application health status, commonly UP or DOWN. Health indicators can reflect application and dependency conditions; details depend on configuration.
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.
Why secure Actuator endpoints?
Some endpoints reveal sensitive application and operational details. Metrics, environment, and bean details can expose internal structure if unsecured.
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.
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.
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.
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.
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.
What does 500 mean?
Internal Server Error. Used for unexpected failures in server processing, unlike a client-side 4xx error.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
What are the five specialized HTTP mapping annotations?
@GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping. GET reads, POST submits, PUT replaces, PATCH modifies part, DELETE removes.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
What does @Id do?
Identifies an entity's primary-key field. The identifier distinguishes entity instances and is used in persistence operations.
What does @GeneratedValue do?
Configures how an entity primary-key value is generated. Strategies include IDENTITY and SEQUENCE, depending on database support and configuration.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.