🟢 Spring Boot: Integration tests ar @SpringBootTest 🧪 Integration Testing in Spring Boot with @SpringBootTest Unit tests verify isolated pieces of logic, but real bugs often hide in the seams — where controllers talk to services, services talk to repositories, and repositories talk to a database. That's where @SpringBootTest shines. @SpringBootTest boots the full Spring application context (or a slice of it) so your tests run against real beans, real configuration, and — with Testcontainers — a real database. No mocking your own code. No fragile assumptions. Key practices I rely on: ▪️ Use webEnvironment = RANDOM_PORT with TestRestTemplate or WebTestClient to hit actual HTTP endpoints ▪️ Combine with @Testcontainers + PostgreSQLContainer instead of H2 — test against the same DB engine you run in production ▪️ Use @DynamicPropertySource to inject container JDBC URLs at runtime ▪️ Reuse the Spring context across tests (avoid @DirtiesContext unless necessary) — startup is the biggest cost ▪️ Seed data with @Sql scripts or test fixtures, and isolate tests with @Transactional rollback where appropriate ▪️ Layer your tests: @WebMvcTest for the web slice, @DataJpaTest for JPA slice, @SpringBootTest for full end-to-end flows Integration tests are slower than unit tests — that's the trade-off. But the confidence they give when refactoring or upgrading Spring Boot versions is worth every extra second in CI. #SpringBoot #Java #IntegrationTesting #Testcontainers #SoftwareEngineering #Backend #TestAutomation #JUnit
Jānis Ošs’ Post
More Relevant Posts
-
#Spring Boot Auto-Configuration (Deep Dive) • Auto-Configuration automatically configures Spring application based on dependencies • Reduces the need for manual bean configuration • Works using classpath scanning and conditional logic • Enabled by @EnableAutoConfiguration How Auto-Configuration Works • Spring Boot checks dependencies present in classpath • Based on dependencies, it loads relevant configuration classes • Uses conditional annotations to decide bean creation • Configurations are defined in spring.factories (or AutoConfiguration imports) Important Conditional Annotations • @ConditionalOnClass • @ConditionalOnMissingBean • @ConditionalOnProperty • @ConditionalOnWebApplication Example Scenario • If spring-boot-starter-web is added • Spring Boot auto-configures: DispatcherServlet Tomcat server Web MVC configuration Key Interview Questions • What is Auto-Configuration in Spring Boot? • How does Spring Boot decide which beans to create? • What is @ConditionalOnMissingBean? • Can we disable Auto-Configuration? If yes, how? Code Example (Disable Auto-Configuration) @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } } Interview Insight • Auto-Configuration follows "Conditional Loading" • It only creates beans if they are not already defined • Developers can override default configuration easily #SpringBoot #Java #BackendDevelopment #InterviewPreparation #SoftwareEngineering
To view or add a comment, sign in
-
One thing I’ve learned building backend systems: Audit logging always starts as a “simple requirement” …and ends up being a complex subsystem. - Who changed what? - When did it happen? - Can we query it efficiently? Most teams either: 1. Over-engineer it 2. Or build something they regret later So I decided to build it properly once. Introducing nerv-audit (now on Maven Central): A Spring Boot audit framework powered by Hibernate Envers, with: - Clean architecture - Queryable audit history - Production-ready design If you're building serious systems, this is something you’ll eventually need. Full write-up here: https://lnkd.in/g2sv9dsM Curious how others are handling audit trails in their systems 👇 #SpringBoot #Java #SoftwareEngineering #Backend #OpenSource
To view or add a comment, sign in
-
⚠️ Hot Reload in Spring Boot Isn’t Magic. It’s ClassLoader Isolation. When you change code and see: 👉 App restarts in seconds 👉 No full JVM restart What’s really happening? 1️⃣ Two ClassLoaders — The Core Idea Spring Boot DevTools splits your app into: Base ClassLoader → dependencies (stable) Restart ClassLoader → your application code (changing) 2️⃣ Why This Matters Dependencies (like Spring, Hibernate): Loaded once Heavy to reload Rarely change Your code: Changes frequently Needs fast reload So only your code is reloaded. 3️⃣ What Happens on Code Change You modify a .class file DevTools detects change (file watcher) Discards Restart ClassLoader Creates a new one Reloads your classes Base ClassLoader stays untouched 4️⃣ Why It’s Faster Than Full Restart Without DevTools: JVM restarts All classes reloaded Framework reinitialized With DevTools: Only your classes reload Dependencies reused Startup drastically reduced 5️⃣ What Actually Gets Restarted? Spring ApplicationContext Beans created again Config reloaded But: 👉 JVM process stays alive 👉 Core libraries remain loaded 6️⃣ Common Gotcha (Very Important) Static state survives in Base ClassLoader. Example: static Map cache = new HashMap(); If loaded by base loader: It won’t reset after reload Leads to weird bugs 7️⃣ Why Some Changes Don’t Reload DevTools won’t reload when: Dependency JAR changes Config outside classpath changes Native resources updated Requires full restart 8️⃣ Comparison With Other Tools Tool Approach DevTools ClassLoader restart JRebel Bytecode rewriting HotSwap Limited JVM replacement DevTools doesn’t “reload classes” It replaces the ClassLoader that loaded them #Java #SpringBoot #JVM #ClassLoader #HotReload #BackendEngineering #SoftwareEngineering #LearnInPublic
To view or add a comment, sign in
-
🚀 Spring Framework 🌱 | Day 17 Exception Handling in Spring Boot (Real Project Approach) In many projects, I’ve seen controllers filled with try-catch blocks. It works… but it quickly becomes messy and hard to maintain. A better approach in Spring Boot is: 👉 Centralized Exception Handling using @ControllerAdvice 💡 It’s important to follow these best practices in real projects. 1️⃣ Create a Global Exception Handler - Use @ControllerAdvice - Handle all exceptions in one place 2️⃣ Define Custom Exceptions - Example: ResourceNotFoundException, BusinessException - Helps in better clarity instead of generic Exception 3️⃣ Standard API Error Response Instead of random messages, always return structured response: { "timestamp": "...", "status": 404, "error": "Not Found", "message": "User not found", "path": "/users/10" } 4️⃣ Map Exceptions Properly - 400 → Bad Request (validation issues) - 404 → Resource not found - 500 → Unexpected errors 5️⃣ Avoid exposing internal details - Never return stack trace in API response (security risk) 🔥 Why this matters? ✔ Cleaner Controllers (no repetitive try-catch) ✔ Consistent API responses ✔ Easy debugging & logging ✔ Production-ready design ⚡ Pro Tip: Combine @ControllerAdvice with proper logging (SLF4J) and monitoring tools for better debugging in production. #SpringBoot #Java #BackendDevelopment #CleanCode #Microservices #SoftwareEngineering
To view or add a comment, sign in
-
-
Part(1/3) Stop using @DataJpaTest for your Spring integration tests. Here is why it is silently lying to you. Most Java backend engineers reach for @DataJpaTest because it feels convenient. It auto-configures everything, and it wraps each test in a @Transactional that rolls back after execution. Clean setup, zero cleanup effort. Sounds perfect. The problem is that rollback-based cleanup fundamentally changes what you are actually testing. When the entire test runs inside a single transaction that never commits, your service layer inherits that transaction context. The EntityManager stays open even after your service method returns. Proxies that would throw a LazyInitializationException in production can still be initialized inside the test because the session is still alive. You write a passing test for code that will crash in production. On top of that, FlushModeType.AUTO only flushes before a commit. If you never commit, some SQL statements never execute at all. Your database constraints never get validated. Your optimistic locking never fires. Your test is testing a reality that does not exist. The correct approach is to let your service layer own transaction boundaries, exactly like it does in production, and clean up test data a different way. Continued in comments
To view or add a comment, sign in
-
Day 84 of 100 — Logging with SLF4J & Logback in Spring Boot 📌 Objective Today I learned how to implement logging in Spring Boot using SLF4J and Logback to track application behavior, debug issues, and monitor performance. 🚀 What is Logging? Logging is used to record application events such as: ✔ Errors ✔ Debug information ✔ Application flow ✔ System activities 🌱 What is SLF4J? SLF4J (Simple Logging Facade for Java) is a logging API that provides a standard interface for different logging frameworks. ✔ Decouples logging implementation ✔ Supports multiple logging frameworks 🌱 What is Logback? Logback is the default logging framework used in Spring Boot. ✔ High performance ✔ Flexible configuration ✔ Supports file & console logging 📘 Using Logger in Spring Boot import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RestController public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @GetMapping("/test") public String test() { logger.info("Test API called"); logger.debug("Debugging information"); logger.error("Error occurred"); return "Logging working!"; } } 📊 Log Levels Level. Purpose TRACE. Detailed information DEBUG. Debugging INFO. General info WARN. Warning ERROR. Errors ⚙️ Configuration (application.properties) Properties logging.level.root=INFO logging.level.com.example=DEBUG 📁 Log Output Example INFO - Test API called DEBUG - Debugging information ERROR - Error occurred 🧠 What I Learned ✔ Importance of logging in applications ✔ Difference between SLF4J and Logback ✔ Using Logger in Spring Boot ✔ Managing log levels for debugging and monitoring 💬 Post Description Day 84 of my 100 Days of Code Challenge! Today I implemented logging in Spring Boot using SLF4J and Logback. Logging helps track application behavior, debug issues, and improve system monitoring. #Day84 #100DaysOfCode #SpringBoot #Logging #SLF4J #Logback #JavaBackend #BackendDevelopment #CodingJourney #LearnJava
To view or add a comment, sign in
-
-
In production Spring Boot services, scattered try-catch blocks create inconsistent API behavior. A better approach is centralized handling: ```@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorResponse> handleNotFound(ResourceNotFoundException ex) { return ResponseEntity.status(HttpStatus.NOT_FOUND) .body(new ErrorResponse("RESOURCE_NOT_FOUND", ex.getMessage())); } @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body(new ErrorResponse("VALIDATION_ERROR", "Invalid request payload")); } @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleGeneric(Exception ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .body(new ErrorResponse("INTERNAL_ERROR", "Unexpected error occurred")); } }``` Benefits we observed: - Consistent contract for error payloads - Cleaner controllers/services - Accurate HTTP semantics (400, 404, 409, 500) - Better observability and incident response A strong error model is part of API design, not just exception handling. #SpringBoot #Java #Microservices #API #SoftwareEngineering #Backend
To view or add a comment, sign in
-
I've seen developers write 200 lines of config code. All of it could've been replaced with 3 annotations. That's the power of Spring Boot — if you know the right annotations. Most developers only scratch the surface. Here's the complete breakdown you actually need: BOOTSTRAP → @SpringBootApplication — main entry point, enables everything → @EnableAutoConfiguration — auto-configures beans from classpath → @ComponentScan — scans and registers Spring components LAYERED ARCHITECTURE → @Component — generic Spring-managed bean → @Service — business logic layer → @Repository — data access with exception translation → @RestController — builds REST APIs returning JSON/XML DEPENDENCY INJECTION → @Autowired — injects dependencies automatically → @Qualifier — resolves ambiguity between multiple beans → @Primary — marks default bean implementation WEB & REST APIs → @GetMapping / @PostMapping / @PutMapping / @DeleteMapping → @RequestBody — maps payload to Java object → @PathVariable — extracts values from URL → @RequestParam — reads query parameters DATABASE & JPA → @Entity — maps class to DB table → @Transactional — ensures atomic operations with rollback → @GeneratedValue — auto-generates primary key VALIDATION → @Valid — triggers validation on request → @NotNull / @NotBlank / @Email / @Pattern — enforce input rules EXCEPTION HANDLING → @ExceptionHandler — handles specific exceptions → @RestControllerAdvice — global error handling for REST APIs SECURITY → @EnableWebSecurity — enables Spring Security → @PreAuthorize — role/permission check before method execution ADVANCED → @Scheduled — runs cron jobs → @Async — executes methods asynchronously → @Cacheable / @CacheEvict — cache and invalidate results I've compiled all of this into a structured PDF carousel. Comment SPRING and I'll send it to your DMs. ♻ Repost if this helped someone on your network. Follow Narendra K. for more Java & Spring Boot content. #SpringBoot #Java #BackendDevelopment #JavaDeveloper #SpringFramework #SoftwareEngineering #WebDevelopment #Programming #InterviewPreparation
To view or add a comment, sign in
-
🚀 DAY 9 — Spring Revision (Day 1 → Day 8) 🔥 Before starting Spring Boot, I revised everything I learned so far 👇 📌 🔁 QUICK REVISION (IMPORTANT POINTS) ✅ Day 1 — Why Spring? Too many technologies earlier (JSP, Servlet, JDBC) Spring reduces complexity Provides one ecosystem for backend ✅ Day 2 — IoC & DI IoC → Spring controls object creation DI → Spring injects dependencies Loose coupling achieved ✅ Day 3 — Spring vs Spring Boot Spring → more configuration Spring Boot → auto configuration + embedded server Boot = faster development ✅ Day 4 — Constructor Injection Dependency passed via constructor Recommended way ✔️ No new keyword ✅ Day 5 — XML vs Annotation XML → old, more config Annotation → modern, less code Needs @ComponentScan ✅ Day 6 — Core Annotations @Component → bean @Service → business logic @Repository → DB @Controller → request @Autowired → DI ✅ Day 7 — Bean Basics Bean = object managed by Spring Created by IoC container Scope: Singleton (default), Prototype ✅ Day 8 — Bean Lifecycle Create → Inject → Init → Use → Destroy @PostConstruct → after init @PreDestroy → before destroy 🎯 🔥 INTERVIEW QUESTIONS (MUST KNOW) ❓ What is Spring? 👉 Framework for building Java applications, reduces complexity ❓ What is IoC? 👉 Control of object creation given to Spring ❓ What is Dependency Injection? 👉 Injecting required objects instead of creating manually ❓ Types of DI? 👉 Constructor, Setter, Field (Constructor preferred) ❓ What is Bean? 👉 Object managed by Spring container ❓ Bean Scope? 👉 Singleton (one object), Prototype (multiple objects) ❓ Bean Lifecycle? 👉 Create → Inject → Init → Use → Destroy ❓ Difference: Spring vs Spring Boot? 👉 Boot reduces configuration, adds embedded server ❓ @Component vs @Service vs @Repository? 👉 Same working, different purpose (layer-wise clarity) ❓ What is @Autowired? 👉 Automatically inject dependency ❓ What is ApplicationContext? 👉 IoC container that manages beans 💡 FINAL UNDERSTANDING 👉 Spring = Manage objects + reduce complexity 👉 IoC + DI = Core of Spring 💬 Did you revise before jumping to Spring Boot? Day 9 done ✅ #Spring #Java #BackendDevelopment #LearningInPublic #30DaysOfCode #SpringBoot #Developers
To view or add a comment, sign in
-
-
🧩Spring Framework 🌱 | Day 19 Spring Boot Exception Handling – Quick Cheat Sheet Here’s a quick cheat sheet 👇 🔹 1. Global Exception Handling 👉 @ControllerAdvice - Central place to handle all exceptions - Keeps controllers clean 🔹 2. Handle Specific Exceptions 👉 @ExceptionHandler @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<?> handleNotFound(...) { } 🔹 3. Custom Exceptions - Create meaningful exceptions ✔ ResourceNotFoundException ✔ BusinessException 🔹 4. Standard Error Response Always return structured response: { "timestamp": "...", "status": 400, "message": "Validation failed", "path": "/api/users" } 🔹 5. Common HTTP Status Codes ✔ 400 – Bad Request ✔ 401 – Unauthorized ✔ 403 – Forbidden ✔ 404 – Not Found ✔ 500 – Internal Server Error 🔹 6. Useful Annotations ✔ @ResponseStatus ✔ @Valid (for validation) ✔ @RestControllerAdvice 🔹 7. Validation Handling 👉 MethodArgumentNotValidException - Capture field-level errors - Return proper messages 🔹 8. Logging (Must Have) - Use SLF4J (log.error) - Never expose stack trace to client 🔹 9. Internal Flow (Quick View) DispatcherServlet → Controller → Exception → HandlerExceptionResolver → Response 🔹 10. Pro Tips ✔ Don’t use try-catch everywhere ✔ Keep error messages user-friendly ✔ Separate technical & business errors 🔥 Clean exception handling = Clean API design #SpringBoot #Java #BackendDevelopment #CheatSheet #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development