Spring ServiceLocator 介绍及应用

在 Spring 中应用 ServiceLocator 方式来获取 Spring Bean 的介绍参考了那么多,其实还是数官方的 ServiceLocatorFactoryBean JavaDoc 文档最言简意该了。Spring 的 ServiceLocator 仿佛用处不大,说到底就是类似于下方找寻某个 Spring Bean 一样:

ApplicationContext context = ...;
Service service = context.getBean(ServiceImpl.class);
Service service = context.getBean("myService");

只是有了 ServiceLocatorFactoryBean(它本质上就是一个 FactoryBean) 后我们不需要直接与 ApplicationContext 打交道,且多个的 Spring Bean 可以从相关的一个 FactoryBean 获得。下面用两个例子来演示(代码中刨去了 package 和 import 部分的代码)

一:实现类只有一个 Spring Bean 时

接口类 Parser(我们要定位就是它的实现类) 阅读全文 >>