如何在不同 类 中多次注入时获得一个依赖实例?
How to get one instance of dependency while it injected several times in different classes?
我需要获取 OwnerService 的一个实例,因为在 Dataloader class 中我将一些数据加载到该实例,而在 OwnerController class 中我必须获取加载的数据。但是在 OwnerController 中没有数据。我打印出实例并收到不同的实例 ID
数据加载器class
public class DataLoader implements CommandLineRunner {
private final OwnerService ownerService;
public DataLoader() {
ownerService = new OwnerServiceMap();
}
@Override
public void run(String... args) throws Exception {
System.out.println(ownerService);
}
}
@RequestMapping("/owners")
@Controller
public class OwnerController {
private final OwnerService ownerService;
public OwnerController(OwnerService ownerService) {
this.ownerService = ownerService;
}
@GetMapping({"", "/", "/index"})
public String ownersIndex(Model model) {
System.out.println(ownerService);
model.addAttribute("owners", ownerService.findAll());
return "owners/index";
}
}
我需要一个 Bean 实例注入多个 classes.
在您的 class DataLoader
中,您没有注射 OwnerService
。相反,构造函数直接创建 class OwnerServiceMap
的实例(大概是实现接口 OwnerService
的 class):
public DataLoader() {
ownerService = new OwnerServiceMap();
}
相反,将其注入 DataLoader
,方法与在 OwnerController
:
中完全相同
public DataLoader(OwnerService ownerService) {
this.ownerService = ownerService;
}
我需要获取 OwnerService 的一个实例,因为在 Dataloader class 中我将一些数据加载到该实例,而在 OwnerController class 中我必须获取加载的数据。但是在 OwnerController 中没有数据。我打印出实例并收到不同的实例 ID
数据加载器class
public class DataLoader implements CommandLineRunner {
private final OwnerService ownerService;
public DataLoader() {
ownerService = new OwnerServiceMap();
}
@Override
public void run(String... args) throws Exception {
System.out.println(ownerService);
}
}
@RequestMapping("/owners")
@Controller
public class OwnerController {
private final OwnerService ownerService;
public OwnerController(OwnerService ownerService) {
this.ownerService = ownerService;
}
@GetMapping({"", "/", "/index"})
public String ownersIndex(Model model) {
System.out.println(ownerService);
model.addAttribute("owners", ownerService.findAll());
return "owners/index";
}
}
我需要一个 Bean 实例注入多个 classes.
在您的 class DataLoader
中,您没有注射 OwnerService
。相反,构造函数直接创建 class OwnerServiceMap
的实例(大概是实现接口 OwnerService
的 class):
public DataLoader() {
ownerService = new OwnerServiceMap();
}
相反,将其注入 DataLoader
,方法与在 OwnerController
:
public DataLoader(OwnerService ownerService) {
this.ownerService = ownerService;
}