Why Spring @Autowired field is null and how to fix it?
Hello everyone. I'm new to Spring and encountered an unclear problem. I have a `UserService` service that I want to inject into a controller using the `@Autowired` annotation. But when trying to call a service method, I get a `NullPointerException` — the `userService` field is `null`.
Here is my code:
```java
public class UserController {
@Autowired
private UserService userService;
public void handleRequest() {
userService.getUser(1); // NullPointerException here
}
}
@Service
public class UserService {
public String getUser(int id) {
return "User " + id;
}
}
```
I also tried using `@Component` on the controller, but that didn't help. I didn't configure anything in `applicationContext.xml` — I thought Spring Boot would handle everything automatically. The project
No answers yet.
Log in to leave an answer