I am building a web application using Java Spring Boot. I'm trying to use a JPA repository in two different controllers. However, it only works inside one controller and not in the other one.
MyRepository.java
public interface MyRepository extends JpaRepository<Favorite, Long> { }
It works fine in OneController without any problem.
OneController.java
@RestController
@RequiredArgsConstructor
public class OneController {
@Autowired
private final MyRepository myRepository;
}
However, when I try to also use it in AnotherController, I get the following message: Variable 'myRepository' might not have been initialized.
AnotherController.java
@Controller
@RequiredArgsConstructor
public class AnotherController {
@Autowired
private MyService myService;
@Autowired
private final MyRepository myRepository;
private final DateUtil dateUtil;
public AnotherController(DateUtil dateUtil) {
this.dateUtil = dateUtil;
}
}
What's the problem here? One is RestController and the other is Controller, but that doesn't seem to be an issue.
EDIT: Sorry for the confusion. I have omitted a constructor in AnotherController in my original question, so I have added it.
For some reason, after removing a constructor, I no longer see the message Variable 'myRepository' might not have been initialized.
Without a constructor, everything works fine. Why is it that?
Also, @Autowired
doesn't seem to be required for repositories, but the service needs it. Without the annotation, the whole page won't work. Why is it the case?
When you're using field autowiring, fields cannot be final. First the instance is created (with null
values), then the autowired fields get updated. That can't be done if they're final.
Since you're using @RequiredArgsConstructor
, you can just remove the @Autowired
. This will make Spring use constructor autowiring; it will find the dependencies when calling the constructor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.