@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