CodexBloom - Programming Q&A Platform

Java 17 Spring Boot Application scenarios to Inject Dependencies with @Autowired in Tests

👀 Views: 37 💬 Answers: 1 📅 Created: 2025-06-12
spring-boot junit dependency-injection Java

I'm performance testing and I'm testing a new approach and I tried several approaches but none seem to work..... I'm working with an scenario with dependency injection in my Spring Boot application while running unit tests. I'm using Java 17 and Spring Boot 2.6.4. When I annotate my test class with `@SpringBootTest`, the dependencies that I expect to be injected using `@Autowired` are coming up as null. Here's an example of my test class: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.assertNotNull; @SpringBootTest public class MyServiceTest { @Autowired private MyService myService; @Test public void testMyServiceInjection() { assertNotNull(myService); } } ``` The `MyService` class is a standard Spring @Service component annotated as follows: ```java import org.springframework.stereotype.Service; @Service public class MyService { // Service logic here } ``` My application context is correctly set up, and the application runs fine outside of tests. I’ve checked my `application.properties` and there’s nothing unusual there. I also tried using `@MockBean` for the dependencies, but it seems unnecessary since I just want to verify simple injection. I’ve looked through the Spring documentation but couldn’t find anything that stood out related to this specific scenario. Has anyone encountered this question before, or could there be an scenario with configuration that I'm overlooking? Any insights would be appreciated! I'm working on a service that needs to handle this. Any help would be greatly appreciated! This is part of a larger application I'm building. What's the best practice here? I'd be grateful for any help. This is part of a larger mobile app I'm building. I'm open to any suggestions.