Ricky Ricky - 5 months ago 20
Java Question

Hashmap is null when returning

I am having a rest controller to consume a web service like below:

@RestController
public class Test{


@Autowired
@Qualifier("restTemplatetest")
private RestTemplate restTemplatetest;

@Bean
public RestTemplate restTemplatetest() {


RestTemplateBuilder buildertest = new RestTemplateBuilder();
RestTemplate buildtest = buildertest.build();

return buildtest;
}


public Map<Integer,Integer> map=new HashMap<Integer,Integer>();



@Scheduled(fixedRate=30000)
public void receiveTestData(){

map.clear();
map=restTemplatetest.getForObject("url",Map.class);
// I get the testdata


System.out.println("size of hashmap after requesting is:" + map.size());// this print s the test data size as 120
}



public Map<Integer,Integer> supplyTestData(){

System.out.println("size of hashmap after requesting is:" + map.size());// this print s the test data size as 0
return map;


}
}


So I want this test data hash map in another controller

So what I do is

@RestController
public class HomeController {
@Autowired
Test test;
Map<Integer,Integer> testmap=new HashMap<Integer,Integer> ();

@Scheduled(fixedRate=40000 ,initialDelay=40000)
public void fetchTestDataHere(){

testMap=test.supplyTestData();


}


But this returns a null.
So my question is I receive the data in the Test Class and it is not null.But when I return the hash map from Test Class it is returning a null value.Why is that?Any help is appreciated.

Answer Source

Thats because Map is tied to the instance of Test object and if you want to access it by auto wiring it, you have to make it static.