Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading