Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/spring-mvc/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring控制器中的缓存填充_Java_Spring Mvc - Fatal编程技术网

Java Spring控制器中的缓存填充

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

我想在服务器启动之前调用所有请求映射方法(具有@Resource注入)。我怎么能做到

@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();
}
}