如何使用@ControllerAdvice @ModelAttribute定位特定的处理程序?
问题内容:
我想在系统关闭前5分钟在特定页面上显示警告消息。我没有手动将其添加到这些页面中,而是使用@ModelAttribute方法创建了一个@ControllerAdvice类,该方法将消息添加到Model参数中,但是据我了解的阅读文档和SO以及对该模型属性的一些初步测试,我们将其添加到每个带有@RequestMapping的方法。
我意识到我可以重构代码,以使目标方法都集中在一个控制器中,并将@ControllerAdvice限制在该控制器中,但最终我会在该控制器中获得其他不相关方法的集合,这会使整个结构变得混乱我的控制器。
那么,有没有办法指出@ModelAttribute应用于多个控制器中的哪个特定方法?自定义注释是否可以解决(不确定如何工作)?如果可能的话,我想通过注释来做到这一点。
编辑:
@ControllerAdvice代码非常基本:
@ControllerAdvice
public class GlobalModelController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Autowired
private MaintenanceInterceptor maintInterceptor;
@ModelAttribute()
public void globalAttributes(Model model, Locale locale) {
if (maintInterceptor.isMaintenanceWindowSet() && !maintInterceptor.isMaintenanceInEffect()) {
String msg = maintInterceptor.getImminentMaint(locale);
model.addAttribute("warningMaint", msg);
logger.debug("maint msg= " + msg);
}
}
}
问题答案:
通过使用@ControllerAdvice
注释的值之一,控制器建议可以限于某些控制器(而非方法),例如
@ControllerAdvice(assignableTypes = {MyController1.class, MyController2.class})
如果您需要在方法级别执行此操作,建议您看一下Interceptors。