我想在服务器启动之前调用所有请求映射方法(具有@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());
}
}
上面的代码失败并给我IllegalStateException。在服务器启动并填充缓存之前调用请求映射方法的最佳方法是什么。
答案 0 :(得分:0)
尝试将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();
}
}