今天在研究异步导出如何注册rmi服务时,看到了一个没见过的写法,@Bean(name=“/xxxx”),即bean的name是以“/”开头,像这样
@Resource
private ExcelManageService excelManageService;
@Bean(name = "/excelManageService")
public HessianServiceExporter excelManageService() {
HessianServiceExporter exporter = new HessianServiceExporter();
exporter.setService(excelManageService);
exporter.setServiceInterface(ExcelManageService.class);
return exporter;
}
经过一段debug发现,@Bean已“/”开头,会将该bean的名称(即那段uri)注册到spring mvc中,并将bean对象放到requestHandlerMap中。
源码步骤探究先简单说一下结果
以“/”开头作为名称的bean,是会被BeanNameUrlHandlerMapping这个类处理的。
BeanNameUrlHandlerMapping继承了AbstractDetectingUrlHandlerMapping,而AbstractDetectingUrlHandlerMapping又是抽象类ApplicationObjectSupport的子类,这个很关键
public abstract class ApplicationObjectSupport implements ApplicationContextAware{
@Override
public final void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
if (context == null && !isContextRequired()) {
// Reset internal context state.
this.applicationContext = null;
this.messageSourceAccessor = null;
}
else if (this.applicationContext == null) {
// Initialize with passed-in context.
if (!requiredContextClass().isInstance(context)) {
throw new ApplicationContextException(
"Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]");
}
this.applicationContext = context;
this.messageSourceAccessor = new MessageSourceAccessor(context);
initApplicationContext(context);
}
else {
// Ignore reinitialization if same context passed in.
if (this.applicationContext != context) {
throw new ApplicationContextException(
"Cannot reinitialize with different application context: current one is [" +
this.applicationContext + "], passed-in one is [" + context + "]");
}
}
}
}
ApplicationObjectSupport提供了向bean自身注册容器的能力和初始化容器时自定义初始化的能力。
而BeanNameUrlHandlerMapping正是在initApplication里做了文章
@Override
public void initApplicationContext() throws ApplicationContextException {
super.initApplicationContext();
// 搜集请求处理器
detectHandlers();
}
我们来看一下detectHandlers方法
protected void detectHandlers() throws BeansException {
ApplicationContext applicationContext = obtainApplicationContext();
String[] beanNames = (this.detectHandlersInAncestorContexts ?
BeanFactoryUtils.beanNamesForTypeIncludingAncestors(applicationContext, Object.class) :
applicationContext.getBeanNamesForType(Object.class));
// Take any bean name that we can determine URLs for.
// 解析beanName中的url
for (String beanName : beanNames) {
String[] urls = determineUrlsForHandler(beanName);
if (!ObjectUtils.isEmpty(urls)) {
// URL paths found: Let's consider it a handler.
// 注册url和对应的bean
registerHandler(urls, beanName);
}
}
if ((logger.isDebugEnabled() && !getHandlerMap().isEmpty()) || logger.isTraceEnabled()) {
logger.debug("Detected " + getHandlerMap().size() + " mappings in " + formatMappingName());
}
}
detectHandlers会从容器中捞取所有的beanName,并判断该beanName包括它的别名是否是以“/”开头,如果是的话,就会将路径和该bean注册到BeanNameUrlHandlerMapping的handlerMap中,key即uri路径,value即bean自己。
当请求到达DisPatchServlet的doDispatch方法时,会依据请求url找到对应的HandlerMapping,再取出其中的Handler(即我们注入的bean),执行具体方法。
// 这段代码是doDispatch中搜索请求处理器的
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
// 循环所有的handlerMappings,BeanNameUrlHandlerMapping就在其列
for (HandlerMapping hm : this.handlerMappings) {
if (logger.isTraceEnabled()) {
logger.trace(
"Testing handler map [" + hm + "] in DispatcherServlet with name '" + getServletName() + "'");
}
// 依据请求url获取对应的handler,当然是包装过的HandlerExecutionChain
HandlerExecutionChain handler = hm.getHandler(request);
if (handler != null) {
return handler;
}
}
return null;
}
需要注意的是,不是所有bean被以“/”开头注入spring容器中,都能正常处理请求,注入的bean必须是HandlerAdapter支持的类型,看下图
如果注入的bean不被上面几种适配器支持,那它就会抛出异常~
- @Bean的name属性以“/”开头
- 注册的bean是HandlerAdapter适配的类的子类
- url不要重复!



