简体   繁体   中英

Providing OSGi Service Without Implementing Interface

Sample 1

@Component(policy = ConfigurationPolicy.OPTIONAL, immediate = false)
public class ServiceImpl implement Service {

  @Override
  public void foo() {

  } 

  ...
}

Sample 2

@Component(policy = ConfigurationPolicy.OPTIONAL, immediate = false)
public class Service {

  public void foo() {
  } 
  ...
}

I have a component which consists some methods. I want to provide a ServiceImpl class which implements Service interface as a OSGi service(in sample 1). However, Service interface is implemented by single class. According to YAGNI design principle, Creating interface for only one class is unneeded. Instead of doing this, creating class which has methods is preferable(in sample 2). If I choose sample one, I will ignore some conventions including YAGNI and class naming(not impl suffix but specific name). If I choose sample 2, It won't suitable for OSGi environment. I am confused what I should do.

Creating a service without an interface is possible and even common in OSGi. I use it a lot to wire internal components that are not visible outside the bundle.

You only need to declare that your component exports the class as a service.

@Component(service=Service.class)
public class Service {

  public void foo() {
  } 
  ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM