在Spring中批量注入策略模式的Bean
1.HandlerMapping
public class DispatcherServlet extends FrameworkServlet {
// 注入方式为List
private List<HandlerMapping> handlerMappings;
// 使用get方法获取需要的bean,符合条件是返回结果不为空
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
for (HandlerMapping mapping : this.handlerMappings) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
}
2.HandlerAdapter
public class DispatcherServlet extends FrameworkServlet {
// 注入方式为List
private List<HandlerAdapter> handlerAdapters;
// 使用supports方法返回需要的bean
protected HandlerAdapter getHandlerAdapter(Object handler) throws ServletException {
if (this.handlerAdapters != null) {
for (HandlerAdapter adapter : this.handlerAdapters) {
if (adapter.supports(handler)) {
return adapter;
}
}
}
throw new ServletException("No adapter for handler [" + handler +
"]: The DispatcherServlet configuration needs to include a HandlerAdapter that supports this handler");
}
}
3.如果需要设置某些处理器的优先级比较高,可以使用Ordered注解设置优先级,ContentNegotiatingViewResolver使用了这一点。