본문 바로가기

IT for researcher/OSGi

What is a servce factory in osgi?

knopflerfish에 설명되어 있는 글을 발번역한 글입니다. 원문 http://www.knopflerfish.org/osgi_service_tutorial.html

OSGi 서비스 팩토리는 ServiceFactory를 구현하면 만들 수 있다.

때때로 서비스는 서비스를 사용하는 번들에 의존하여 다양하게 설정될 필요가 있다. 예를 들어, 로그 서비스는 번들의 아이디를 출력할 수 있을 필요가 있다. 그렇지 않으면 읽기 어려울 것이다.

서비스 팩토리는 일반적인 서비스와 같은 방법으로 registerService를 사용하여 등록된다. 유일한 차이점은 실제적인 서비스 객체를 다루기전에 인디렉션 스텝이라는 것이다.

서비스를 사용하는 클라이언트는 서비스가 팩토리 객체인지 일반객체인지 알 필요도 없고 알아서도 안된다.

간단한 서비스 팩토리 예제

  class LongFactory implements ServiceFactory {
    public Object getService(Bundle bundle, ServiceRegistration reg) { 
       // 번들의 ID를 리턴하도록 구현
       return new Long(bundle.getBundleId());
    }
    void ungetService(Bundle bundle, ServiceRegistration reg, Object service) {
       // nothing needed in this case
    }
  }
   //서비스 등록시 다음과 같이 등록합니다.
  ServiceFactory factory = new LongFactory();
  bc.registerService(Long.class.getName(), factory, new Hashtable());


BundleContext.getService(ServiceReference reference) 에서 등록된 서비스가 ServiceFactory를 구현한 객체이면 ServiceFactory.getService(Bundle, ServiceRegistration)를 호출한다. 결국 ServiceFactory를 이용하여 Customized Object를 서비스로 리턴할 수 있다.