如何在启动后访问应用程序中任何位置的对象
how to access object anywhere in the application after startup
我在 class 的地图中列出了一些国家/地区。现在我想在其他 classes.
的应用程序中访问此地图
基本上我希望这张地图在整个应用程序中可用。
我在启动后立即在启动应用程序中获取国家列表。但能够将其设置为应用范围。我正在使用 spring 引导和网络。
下面是我的代码。
@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;
}
}
在 countrydataLoader class 我正在加载所有国家数据。如何在其他一些 restcontroller 中访问这两个地图?
谢谢
CountryDaoLoader
是一个 spring bean,您可以从应用程序上下文中获取 spring bean 的实例,如下所示。
ApplicationContextProvider.getApplicationContext().getBean(CountryDataLoader.class);
我在 class 的地图中列出了一些国家/地区。现在我想在其他 classes.
的应用程序中访问此地图基本上我希望这张地图在整个应用程序中可用。
我在启动后立即在启动应用程序中获取国家列表。但能够将其设置为应用范围。我正在使用 spring 引导和网络。
下面是我的代码。
@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;
}
}
在 countrydataLoader class 我正在加载所有国家数据。如何在其他一些 restcontroller 中访问这两个地图? 谢谢
CountryDaoLoader
是一个 spring bean,您可以从应用程序上下文中获取 spring bean 的实例,如下所示。
ApplicationContextProvider.getApplicationContext().getBean(CountryDataLoader.class);