Home > Blockchain >  How to get one instance of dependency while it injected several times in different classes?
How to get one instance of dependency while it injected several times in different classes?

Time:03-22

I need to get one instance of OwnerService, because in Dataloader class I load some data to that instance and in OwnerController class I have to get loaded data. But in OwnerController there was no data. I printed out the instances and receive different ID of instances

Dataloader 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";
    }
}

I need one instance of Bean in several injected classes.

CodePudding user response:

In your class DataLoader, you are not injecting OwnerService. Instead, the constructor directly creates an instance of class OwnerServiceMap (which is presumably a class that implements interface OwnerService):

public DataLoader() {
    ownerService = new OwnerServiceMap();
}

Instead, inject it into DataLoader, in exactly the same way as you are doing in OwnerController:

public DataLoader(OwnerService ownerService) {
    this.ownerService = ownerService;
}
  • Related