Spring or Spring Boot
SpringBootServletInitializer TipBoot doesn't replace Spring. It configures it, and you override what doesn't fit.
java -jar starts the app.@Transactional, @Async and @Cacheable work through a proxy. A call from inside the same class skips the proxy, and the feature with it.SpringBootServletInitializer TipBoot doesn't replace Spring. It configures it, and you override what doesn't fit.
spring-boot-starter-webmvcspring-boot-starter-webdata-jpa, security, test or actuatorstart.spring.ioTipLeave the versions off. Boot's dependency management picks them.
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScanTip@Spring combines all three.
TrapScanning starts at the main class's package. Put that class in a root package above your other classes.
Asked in interviews
AskedExplain the @SpringBootApplication annotation.mvn spring-boot:run./gradlew bootRunmvn clean packagejava -jar app.jarjava -jarTipThe embedded server is Tomcat by default, or Jetty. Boot 4 dropped Undertow.
TrapThe server listens from step 5, so a request can arrive while the runners still work.
Asked in interviews
AskedWhat happens when a Spring Boot application starts?ApplicationContext Creates singletons at startup, unlike BeanFactorySpringApplicationBuilder A child sees its parent's beans, not the reverseTrapCall new for a dependency and tests can't mock it.
@Autowiredrequired = false@Qualifier@Primary@Autowired@Inject@Inject is JSR-330, and @Named picks one@ResourceJSR-250, not on a constructorTipConstructors allow final fields and easy tests. Field injection hides what a class needs, so avoid it.
TrapEvery injection point is required by default, so startup fails when no bean matches.
@Component, or by layer @Service, @Repository, @Controller@BeanA method in a @Configuration class@ImportResourceTip@Repository also translates database exceptions into Data.
singletonprototyperequest, session, application, websocketTipA singleton is shared by every thread, so it should hold no changing state.
TrapA prototype injected into a singleton is injected once. Inject an ObjectProvider to get a fresh one.
Asked in interviews
AskedExplain the different bean scopes in Spring.BeanFactoryPostProcessor BeanPostProcessor TrapPrototype beans get no shutdown callbacks. Spring doesn't track them.
BeanCurrentlyInCreationException @LazyA proxy fetches the bean on first callTipThe better fix removes the cycle. Move shared logic to a third bean, or publish an event.
Asked in interviews
AskedHow does Spring handle circular dependencies?@Value("${app.name}") @ConfigurationProperties SERVER_PORT then sets server.portapplication-dev.properties @Profile("prod")--spring.profiles.active=prod SPRING_PROFILES_ACTIVE=prod TrapKeep secrets out of profile files. Supply them as environment variables, or from a secret store.
TrapAn external application. beats a packaged application-prod..
Asked in interviews
AskedExplain Spring Boot's configuration precedence.logging.level.com.example=DEBUG logging.file.name=app.log TrapSpring extensions don't work in plain logback.xml. Use logback-spring..
Asked in interviews
AskedExplain Spring Boot's logging configuration.@ConditionalOnClass @ConditionalOnMissingBean @ConditionalOnProperty spring.autoconfigure.exclude --debugIt prints the conditions reportTipYour configuration runs first, so @Conditional sees your bean and backs off.
@Conditional(MyCheck.class) MyCheck implements ConditionAutoConfiguration.imports spring.factories Removed in Boot 3Tip@Profile is built on @Conditional. Test your class with Application.
BufferingApplicationStartup Read Actuator's startup endpointspring.main.lazy-initialization=true TipHeavy @PostConstruct work blocks startup. Move it to first use or a background task.
TrapWith lazy initialization, a misconfigured bean fails on first use, not at startup.
DispatcherServlet HandlerMappingHandlerAdapterViewResolverHttpMessageConverter Trap@EnableWebMvc switches off Boot's MVC auto-configuration. Implement Web without it.
@ControllerIt returns a view name@RestController@Controller plus @ResponseBodyRouterFunction@GetMapping@PostMapping@PutMapping@PatchMapping@DeleteMappingTrap@RequestMapping with no method matches every HTTP method. Keep it for a class's path prefix, and use the shortcuts on methods.
@PathVariable Long id@RequestParam String q@RequestBody User userResponseEntityTrapParameters are required by default. A missing one, or one that won't convert, ends in 400 Bad Request.
@NotBlank@Valid@ControllerAdvice @ExceptionHandler ProblemDetailTipA failed check throws Method, and the client gets 400 Bad Request.
TrapThe web starter doesn't include validation. Add spring-boot-starter-validation yourself.
MultipartFileResourceWith Content-Disposition: attachmentTrapString doesn't stop path traversal. Check that the normalized path stays in the upload folder.
Asked in interviews
AskedHow do you implement file upload and download in Spring Boot?RestClientRestTemplateDeprecated in Spring 7.1WebClientMono<User>Flux<User>WebFlux, on Netty by defaultTrapOne blocking call, such as plain JDBC, stalls an event loop thread and delays every request on it.
@Entity@IdJpaRepositoryCrudRepositoryTrapSince Spring Data 3.0, Paging brings no CRUD methods.
findByLastNameexistsByEmail@Query("SELECT u FROM User u")nativeQuery = true runs plain SQL@ModifyingRun it in a transactionPageableSpring MVC reads page, size, sortPage<User>Slice<User>TipSpring checks property names when it creates the repository, so a typo fails at startup.
TrapSpring doesn't validate sort values. Check them against allowed property names.
@Transactional(readOnly = true)Hibernate skips dirty checkingREQUIREDREQUIRES_NEWTrapOnly unchecked exceptions roll back by default. A checked exception commits unless rollbackFor names it.
Asked in interviews
AskedExplain Spring Boot's transaction management.spring-boot-starter-flywayflyway-coreV2__Add_phone.sql TipWith migrations, set ddl-auto to validate or none, so Hibernate never changes the schema.
TrapNever edit a script after it has run, because Flyway compares checksums. Add a new script.
Asked in interviews
AskedHow do you implement database migration in Spring Boot?final methodsTrapA final method runs on the proxy itself and skips the advice.
Asked in interviews
AskedWhat is the difference between JDK dynamic proxy and CGLIB proxy?@Aspect holds the advice, and a pointcut picks the methods@Before@After@AfterReturning@AfterThrowing@AroundTrapForget proceed() in @Around and the method silently doesn't run.
@Cacheable@CachePut@CacheEvictTipTurn it on with @EnableCaching.
TrapThe default Concurrent cache never expires entries.
Asked in interviews
AskedHow do you configure and use caching in Spring Boot?@EnableAsync@AsyncCompletableFuture ApplicationEventPublisher @EventListener@TransactionalEventListener TrapEvents are synchronous by default. publishEvent blocks until every listener finishes.
SecurityContextHolder keeps the resultformLoginhttpBasicIt needs HTTPSTipThe starter alone locks every endpoint behind a generated password.
TrapA logged-in user without the role gets 403 Forbidden, not a login redirect.
permitAll()hasRole("ADMIN") BCryptPasswordEncoder UserDetailsService @PreAuthorizeTipTurn CSRF off only for a stateless API that doesn't use cookies.
TrapSpring checks requestMatchers in order, so put specific paths before anyRequest().
Asked in interviews
AskedHow do you implement security in Spring Boot?FilterChainProxy It runs only the first SecurityFilterChain that matchesExceptionTranslationFilter oauth2ResourceServer A JwtDecoder checks signature and expiryOncePerRequestFilter Use STATELESS sessionsTipAdd your own filter with addFilterBefore.
TrapSpring Boot also registers a @Component filter with the servlet container. Turn that off with set on a Filter.
@InjectMocksTest one class@WebMvcTestTest a controller@DataJpaTestTest a repository@SpringBootTestLoad it all in MOCK modeRANDOM_PORTStart the real serverTipThe other modes are DEFINED_PORT and NONE.
TrapWith a real server, a @Transactional test can't roll back what the server wrote.
@Mock@MockitoBean@MockBeanRemoved in Boot 4MockMvc@AutoConfigureTestRestTemplate Trap@WebMvcTest skips @Service and ordinary @Component beans, so you mock each dependency.
/actuator/health /actuator/metrics /actuator/httpexchanges Boot 3 renamed it from httptracemanagement.endpoints.web.exposure.include HealthIndicatorTrapOnly health is exposed over HTTP by default. In production, set show-details to when-authorized.
@EnableConfigServer @CircuitBreakerIt returns a fallbackTrapWithout a circuit breaker, one failing service can make its callers fail too.
Nothing matches. Try a shorter word, or clear the search.
With Pro, you can:
Already have Pro? Sign in