栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

记@Bean的一个妙用:注册远程服务

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

记@Bean的一个妙用:注册远程服务

序

今天在研究异步导出如何注册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不被上面几种适配器支持,那它就会抛出异常~

总结:如何注册一个远程服务
  1. @Bean的name属性以“/”开头
  2. 注册的bean是HandlerAdapter适配的类的子类
  3. url不要重复!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/929543.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号