@Injected public void aServicingMethod(Service s1, AnotherService s2) { // 将s1和s2保存到类变量,须要时可使用 }反转控制容器将查找Injected注释,使用请求的参数调用该方法。咱们想将IoC引入Eclipse平台,服务和可服务对象将打包放入Eclipse插件中。插件定义一个扩展点 (名称为com.onjava.servicelocator.servicefactory),它能够向程序提供服务工厂。当可服务对象须要配置时,插件向一个工厂请求一个服务实例。ServiceLocator类将完成全部的工做,下面的代码描述该类(咱们省略了分析扩展点的部分,由于它比较直观):
public static void service(Object serviceable) throws ServiceException { ServiceLocator sl = getInstance(); if (sl.isAlreadyServiced(serviceable)) { // prevent multiple initializations due to // constructor hierarchies System.out.println("Object " + serviceable + " has already been configured "); return; } System.out.println("Configuring " + serviceable); // Parse the class for the requested services for (Method m : serviceable.getClass().getMethods()) { boolean skip = false; Injected ann = m.getAnnotation(Injected.class); if (ann != null) { Object[] services = new Object[m.getParameterTypes().length]; int i = 0; for (Class<?> class : m.getParameterTypes()) { IServiceFactory factory = sl.getFactory(class, ann .optional()); if (factory == null) { skip = true; break; } Object service = factory.getServiceInstance(); // sanity check: verify that the returned // service's class is the expected one // from the method assert (service.getClass().equals(class) || class .isAssignableFrom(service.getClass())); services[i++] = service; } try { if (!skip) m.invoke(serviceable, services); } catch (IllegalAccessException iae) { if (!ann.optional()) throw new ServiceException( "Unable to initialize services on " + serviceable + ": " + iae.getMessage(), iae); } catch (InvocationTargetException ite) { if (!ann.optional()) throw new ServiceException( "Unable to initialize services on " + serviceable + ": " + ite.getMessage(), ite); } } } sl.setAsServiced(serviceable); }
“七”乐无穷,尽在新浪新版博客,快来体验啊~~~请点击进入~html