Java Spring控制器中的缓存填充
我想在服务器启动之前调用所有请求映射方法(具有@Resource注入)。我怎么能做到Java Spring控制器中的缓存填充,java,spring-mvc,Java,Spring Mvc,我想在服务器启动之前调用所有请求映射方法(具有@Resource注入)。我怎么能做到 @Controller public class ServiceController { @Resource(name="userService") private IUserService userService; @RequestMapping("/getAllCountry") public String getAllCountry() { r
@Controller
public class ServiceController {
@Resource(name="userService")
private IUserService userService;
@RequestMapping("/getAllCountry")
public String getAllCountry() {
return userService.getAllCountry();
}
@RequestMapping("/getAllStates")
public String getAllStates() {
return userService.getStates();
}
@PostConstruct
public void cacheData(){
cache.put("ALL_COUNTRY_DATA", getAllCountry());
cache.put("ALL_STATE_DATA", getAllStates());
}
}
上面的代码失败,并给我非法状态异常。在服务器启动并填充缓存之前调用请求映射方法的最佳方法是什么。尝试将
ApplicationListener
与ContextRefreshedEvent
结合使用:
@Controller
public class ServiceController implements ApplicationListener<ContextRefreshedEvent> {
private static final Map<String, String> cache = new HashMap<>();
@Resource(name = "userService")
private IUserService userService;
@RequestMapping("/getAllCountry")
public String getAllCountry() {
return userService.getAllCountry();
}
@RequestMapping("/getAllStates")
public String getAllStates() {
return userService.getStates();
}
public void cacheData() {
cache.put("ALL_COUNTRY_DATA", getAllCountry());
cache.put("ALL_STATE_DATA", getAllStates());
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
cacheData();
}
}
@控制器
公共类ServiceController实现ApplicationListener{
私有静态最终映射缓存=新HashMap();
@资源(name=“userService”)
专用IUSERSERSERVICE用户服务;
@请求映射(“/getAllCountry”)
公共字符串getAllCountry(){
返回userService.getAllCountry();
}
@请求映射(“/GetAllState”)
公共字符串getAllState(){
返回userService.getStates();
}
公共void cacheData(){
cache.put(“所有国家/地区数据”,getAllCountry());
cache.put(“ALL_STATE_DATA”,getAllStates());
}
@凌驾
ApplicationEvent(ContextRefreshedEvent事件)上的公共无效{
cacheData();
}
}