I have some countries list in map in a class. Now I want to access this map in my application in some other classes.
Basically I want this map available throughout the application.
I am getting countries list in boot application just after startup. But able to set it to application scope. I am using spring boot and web.
Below is my code.
@SpringBootApplication
public class FinalApplication {
public static void main(String[] args) {
ApplicationContext context = new SpringApplicationBuilder(FinalApplication.class).run(args);
Country cfg = context.getBean(Country.class);
CountryDataLoader loader = new CountryDataLoader(cfg);
}
@ApplicationScope
@Component
@NoArgsConstructor
public class CountryDataLoader {
Map<String,List<String>> regionMap = new HashMap<>();
Map<String,List<String>> languageMap = new HashMap<>();
public List<String> countryListByAmericaRegion () {
//System.out.println(myConfig.getList());
List<CountryBean> list = myConfig.getList();
Iterator<CountryBean> it = list.iterator();
while(it.hasNext()) {
CountryBean bean = it.next();
if(bean.getRegion().equals(AMERICAS)) {
byAmericaRegion.add(bean.getCountryName());
}
}
regionMap.put(AMERICAS, byAmericaRegion);
//System.out.println(byAmericaRegion);
return byAmericaRegion;
}
}
In countrydataLoader class I am loading all country data. how to access those two maps in some other restcontrollers? Thanks
CountryDaoLoader
is a spring bean and you can get the instance of a spring bean from application context as shown below.
ApplicationContextProvider.getApplicationContext().getBean(CountryDataLoader.class);