Spring
Recruitment and knowledge question base. Filter, search and test your knowledge.
easydiinversion-of-controlspring+1
Answer
Dependency Injection means an object receives its collaborators from the outside (typically via constructor) instead of creating them with new. In Spring the IoC container instantiates beans, wires dependencies, and manages lifecycles, reducing coupling and improving testability.
@Service
class UserService(private val userRepository: UserRepository) {
fun getUser(id: Long): User {
return userRepository.findById(id).orElseThrow()
}
}mediumannotationconfigurationbean+1
Answer
@Component marks a class for component scanning so Spring registers it automatically as a bean. @Bean is used on a method inside a @Configuration class to register the returned object as a bean, often for third‑party types or custom instantiation. Both become managed beans.
easyspring-bootdependencyconfiguration
Answer
Starters are curated dependency bundles that pull in the typical libraries (and compatible versions) for a feature. For example spring-boot-starter-web adds Spring MVC, Jackson and an embedded server. They simplify setup and work with auto‑configuration.
mediumbeanscopelifecycle+1
Answer
Bean scope defines how long and how widely a bean instance lives. The default is singleton (one instance per container). Prototype creates a new instance per injection. In web apps there are also request, session and application scopes.
hardtransactionaopdatabase+1
Answer
@Transactional is implemented via Spring AOP proxies: before entering the method Spring opens a transaction, and on exit it commits or rolls back based on exceptions and rollback rules. Propagation and isolation are configurable; self‑invocation bypasses the proxy.
easydiiocconstructor-injection
Answer
Spring creates objects (beans) and injects their dependencies, so code depends on abstractions, not manual wiring. Constructor injection makes dependencies explicit, supports immutability (`final`), and is easiest to test.
@Service
class UserService {
private final UserRepository repo;
UserService(UserRepository repo) {
this.repo = repo;
}
}easycomponentservicerepository
Answer
All are stereotypes for component scanning; the main difference is intent. `@Service` marks business logic, `@Repository` marks persistence and can translate persistence exceptions, and `@Component` is generic.
easyrestcontrollercontrollerspring-mvc
Answer
`@RestController` is basically `@Controller` + `@ResponseBody`, so methods return the response body (often JSON) directly. `@Controller` is typically used for server-rendered views/templates.
mediumbeanscopesingleton+1
Answer
`singleton` (default) means one bean instance per Spring container. `prototype` means a new instance each time the bean is requested; for web apps you also have request/session scopes.
mediumtransactiontransactionalrollback
Answer
It runs the method inside a transaction; by default Spring rolls back on unchecked (`RuntimeException`) errors. A common gotcha is self-invocation: calling a `@Transactional` method from the same class bypasses the proxy, so the transaction may not start.
@Service
class PaymentService {
@Transactional
public void pay() {
// DB writes here
}
}mediumspring-bootauto-configurationstarter
Answer
Boot auto-configures beans based on what’s on the classpath and your properties (so you get sensible defaults). Starters are dependency bundles (e.g., `spring-boot-starter-web`) that pull common libraries and enable related auto-config.
hardaopproxytransactional
Answer
Spring AOP usually works via a proxy around your bean. If a method inside the same class calls another advised method directly (`this.someMethod()`), it bypasses the proxy, so aspects like `@Transactional` may not apply.
hardcontrolleradviceexceptionhandlererror-handling
Answer
Use `@ControllerAdvice` with `@ExceptionHandler` to map exceptions to consistent HTTP responses (status + body). It keeps controllers clean and centralizes error handling.
@ControllerAdvice
class ApiErrors {
@ExceptionHandler(IllegalArgumentException.class)
ResponseEntity<String> badRequest(IllegalArgumentException e) {
return ResponseEntity.badRequest().body(e.getMessage());
}
}hardspring-securityfiltersauth
Answer
Mainly in the security filter chain, before the request reaches controllers. Filters build the `SecurityContext` (authentication), then authorization checks decide if access is allowed (URL rules, method security, etc.).
hardtestingwebmvctestspringboottest
Answer
`@WebMvcTest` is a slice test: it loads MVC components (controllers, filters) and is fast, usually with mocked dependencies. `@SpringBootTest` loads the full application context and is better for integration tests, but slower.
easyconfigurationbeanspring-core
Answer
`@Configuration` marks a class that defines Spring beans. `@Bean` marks a method whose return value should be managed by Spring as a bean (created, injected, lifecycle handled).
@Configuration
class AppConfig {
@Bean
Clock clock() {
return Clock.systemUTC();
}
}mediumspring-mvcrequestparampathvariable+1
Answer
Use `@PathVariable` for identifiers that are part of the resource path (e.g., `/users/{id}`). Use `@RequestParam` for optional filters, pagination, or query options (e.g., `?page=2&sort=name`).
@GetMapping("/users/{id}")
UserDto getUser(@PathVariable String id, @RequestParam(defaultValue = "false") boolean verbose) {
return service.get(id, verbose);
}mediumvalidationbean-validationjakarta+1
Answer
`@Valid` triggers Bean Validation (Jakarta Validation) for a request body/parameter based on annotations like `@NotNull`, `@Size`. Validation runs on the server, before your controller method fully processes the object; errors map to 400 responses (often via exception handlers).
hardjpahibernaten-plus-one+1
Answer
N+1 is when you load N parent entities and then trigger one extra query per entity (lazy loading). Reduce it with fetch joins, `@EntityGraph`, batching, or redesigning queries to load needed data in fewer round-trips.
hardtransactionpropagationspring+1
Answer
`REQUIRED` means: join an existing transaction if there is one; otherwise start a new transaction. It’s the default because it composes well for typical service-to-service calls.
easyprofilesconfigurationspring
Answer
`@Profile` conditionally enables beans based on the active profile (e.g., `dev`, `test`, `prod`). It helps you swap implementations/config per environment without changing code.
mediumscheduledclusterdistributed-lock+1
Answer
If you run multiple instances, each one will execute the scheduled job, causing duplicates. Avoid it with leader election, a distributed lock (carefully), a single dedicated scheduler instance, or moving scheduling to an external system.
mediumspring-datapaginationpage+1
Answer
`Page` includes total count and total pages (requires an extra count query). `Slice` only knows if there’s a next page (no total count), so it’s cheaper. Use `Slice` when you don’t need totals and want better performance.
hardasyncexecutorproxy+1
Answer
Spring runs the method on a separate executor via a proxy. A common gotcha is self-invocation (calling the method from the same class) which bypasses the proxy, so it won’t run async. Also remember to size the executor.
hardspring-securitysecuritycontextthreadlocal+1
Answer
SecurityContext is often stored in a ThreadLocal. When you switch threads (async/executor), the new thread may not have that context, so auth info is missing. You must propagate context explicitly or use supported async security integration.
easyspringiocapplicationcontext+1
Answer
The `ApplicationContext` is Spring’s IoC container: it creates, wires, and manages beans (including their lifecycle) and lets you look them up by type/name.
mediumspring-bootconfigurationproperties+1
Answer
`@ConfigurationProperties` binds a group of config values into a typed class, so it’s easier to validate, refactor, and test. It keeps configuration structured (one prefix) and avoids scattering string keys across the codebase.
mediumspringbeanslifecycle+2
Answer
`@PostConstruct` runs after the bean is created and dependencies are injected. `@PreDestroy` runs when the application context is shutting down (for beans it manages, typically singletons). A common gotcha: Spring doesn’t automatically call destroy callbacks for prototype-scoped beans.
hardspringbeanpostprocessoraop+1
Answer
A `BeanPostProcessor` is a hook that can modify or wrap beans before/after initialization. Spring uses it for features like AOP proxies, `@Async`, and `@Transactional`. You’d use it for cross-cutting behavior, but it’s powerful and easy to overuse.
hardspringmvcwebflux+1
Answer
Spring MVC is servlet-based and typically uses one thread per request; it’s great for most CRUD apps and works well with blocking libraries. WebFlux is reactive and non-blocking, which can help with high concurrency and streaming—if your whole stack is non-blocking. Using WebFlux with blocking calls often removes its benefits.
easyspringmvcrequestbody+1
Answer
`@RequestBody` binds the HTTP request body (usually JSON) to an object using an `HttpMessageConverter` (often Jackson). A common pitfall is missing or wrong `Content-Type: application/json`, which can lead to 415/400 errors. You can combine it with `@Valid` to validate input.
mediumspring-bootactuatorobservability+1
Answer
Actuator adds operational endpoints like health checks, metrics, and info (e.g., `/actuator/health`, `/actuator/metrics`). It helps monitoring and debugging, but it can leak sensitive data (env, config, internals), so you should restrict access and expose only what you need.
mediumspring-bootconfigurationprofiles+1
Answer
At a high level, more specific sources override defaults: command-line args and environment variables typically override `application.yml`, and profile-specific config (e.g., `application-prod.yml`) overrides the base file when that profile is active. Spring resolves properties from multiple places and the higher-precedence one wins.
hardspringcachecacheable+1
Answer
`@Cacheable` caches the result of a method call under a key (usually based on arguments). It’s implemented via proxies/AOP. Common gotchas: self-invocation bypasses the proxy (no caching), and caching can serve stale data unless you evict/invalidate (`@CacheEvict`) or set a TTL in the cache provider.
hardspringtransactionsisolation+1
Answer
`isolation` maps to the database isolation level (how concurrent reads/writes interact). `readOnly = true` is usually a hint for the framework/driver to optimize, but it does not automatically prevent writes in all cases. Also remember: `@Transactional` works via proxies, so it won’t apply on self-invocation.
mediumspring-bootauto-configurationstarters+1
Answer
Spring Boot uses `@EnableAutoConfiguration` plus conditional annotations to configure beans based on the classpath and properties (e.g., `@ConditionalOnClass`, `@ConditionalOnProperty`). Starters bring in dependencies, and auto‑config creates sensible defaults you can override.
mediumspring-bootconfigurationproperties+1
Answer
`@ConfigurationProperties` is better for binding groups of related settings into a typed object, supports nested properties and validation, and keeps config cohesive. `@Value` is fine for single values, but it’s less type‑safe for large configs.
@ConfigurationProperties(prefix = "app")
public class AppProps {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}easyspringprofilesconfiguration+1
Answer
`@Profile` enables or disables beans based on the active profile (e.g., `dev`, `test`, `prod`). Use it for environment‑specific beans like mock clients, different data sources, or local‑only configs.
mediumspringdiqualifier+1
Answer
`@Primary` marks the default bean when multiple candidates match. `@Qualifier` lets you choose a specific bean by name/qualifier at the injection point. You can combine them: use `@Primary` as default, and override with `@Qualifier` where needed.
easyspringmvccontroller+1
Answer
`@RestController` is `@Controller` + `@ResponseBody`, so return values are written to the HTTP response (typically JSON). `@Controller` is used for MVC views and typically returns a view name unless you add `@ResponseBody`.
mediumspringlifecyclepostconstruct+1
Answer
`@PostConstruct` runs after dependency injection to perform initialization (e.g., validate config, warm caches). `@PreDestroy` runs when the context shuts down to release resources. They’re lifecycle hooks managed by the container.
hardspringasyncexecutor+1
Answer
`@Async` runs a method in a separate thread via a Spring proxy and an `Executor`. Common pitfalls: it doesn’t work on self‑invocation, it requires a public method on a Spring bean, and blocking I/O can still exhaust the thread pool if not sized properly.
mediumspringschedulingcron+1
Answer
fixedRate schedules the next run based on the start time of the previous run (can overlap if too slow). fixedDelay schedules based on the completion time of the previous run (no overlap). cron lets you use cron expressions for calendar‑based schedules.
mediumspringwebclientresttemplate+1
Answer
WebClient is the newer, non‑blocking reactive client (good for WebFlux and async IO). RestTemplate is blocking and in maintenance mode. For new code, prefer WebClient unless you deliberately want blocking behavior.
mediumspringiocapplicationcontext+1
Answer
BeanFactory is the minimal IoC container (lazy by default). ApplicationContext builds on it with extra features like internationalization, event publishing, and eager singleton initialization. In most apps you use ApplicationContext.