简体   繁体   中英

Access to Spring Boot / MongoDB controller-classes from other classes

I'm making a REST API with Spring Boot and MongoDB in Java.

I've got, for instance, a Location class, with a corresponding LocationRepository and LocationController classes. To access the Location-database (LocationRepository), I need to do it through the LocationController (as far as I know). I've got functions in this controller that run on POST/GET requests, and it's working just fine when sending requests from the front-end server (Nuxt.js w/ Axios) or just through Insomnia/Postman.

However, if I wan't to access the Location-database from the backend, and from another class in my program, I'm not sure how to do it. I suppose I either need to send API-requests locally, or I need to get the actual instance of my LocationController to run functions on it.

Is sending API-requests locally like this bad practice?

Can I somehow get a hold of the instance of my LocationController? This is all managed through Spring, which I assume instanciates the controllers somewhere, but I have no idea where, or how to get a hold of them.

Here is an example of one of my controllers:

@RestController
@RequestMapping("api/locations")
public class LocationController {
    @Autowired
    private LocationRepository repository;

    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public List<Location> getAllLocations(@RequestBody String body) {
        return repository.findAll();
    }

}

Appreciate any help!

EDIT: Using @Autowired LocationController locationController in any class that needs access to this seems to work.

You don't have to instantiate your controller, your repository is in charge of fetching data from database. You can do exctly the same that you're doing inside your controller:

public class MyGreatClass{
    @Autowired
    private LocationRepository repository;
    public void myGreatMethod() {
        List<Location> locations = repository.findAll();
        // Do the stuff with location
    }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM