Home > OS >  Access member variables in Spring ResponseBody
Access member variables in Spring ResponseBody

Time:06-27

I'm new to Spring and this is my question. I want to access a created list everytime a specific route is called. The list is created by a csv file, and I want to create the list only once. (I know hot to create a list from csv). I don't understand when and if the cunstructor of the controller is called, and I don't know if everytime the route is called, it uses another instance of the controller?

@Controller
public class Controller {

    List<List<String>> csvAsList; // how to initialize this list?

    public Controller(List<List<String>> csvAsList) {
        this.csvAsList = csvAsList;
    }


    @RequestMapping(value = "home/{userTypedRoute}")
    @ResponseBody
    public String printRoute(@PathVariable String userTypedRoute){
        //access the list
        return userTypedRoute;
    }

}

CodePudding user response:

How often it will be instantiated will depend on the scope that is used, but I do believe the default scope is "singleton", meaning that there will only be a single instance.

Please, do check the documentation: https://www.baeldung.com/spring-bean-scopes

CodePudding user response:

Use dependency injection for that

create some sort of provider of your list

@Component
class MyListProvider{
    private final List<List<String>> myList;
    public MyListProvider(){
        myList=createYourListSomehow_YouSaidYouKnowHowToDoIt();
    }

    public List<List<String>> getMyList(){
       return myList
    }    
}

and use it in your controller

@Controller
public class Controller {

    private MyListProvider myProvider;

    public Controller(MyListProvider myProvider){ //injection will happen here
        this.myProvider=myProvider;
    }


    @RequestMapping(value = "home/{userTypedRoute}")
    @ResponseBody
    public String printRoute(@PathVariable String userTypedRoute){
        this.myProvider.getMyList(); //here you go
        return userTypedRoute;
    }
    
}
  • Related