简体   繁体   中英

JAVA 6 ServiceLoader

I recently posted a question regarding a way to define the implementation of an abstract service on the client side.

dfa mentioned java.util.ServiceLoader as a solution for my problem.

I ended up going in a similar way, though not using ServiceLoader directly, mainly because i was using JDK 5. But another SOer jut went into panic when dfa mentioned ServiceLoader.

I am wondering what are the main problems with the ServiceLoader implementation. Though limited it seems a good way to solve this issue without going full out on some third party library like Guice

ServiceLoader was added to java.util in JDK6, prior to that the basic technology was used in the Service class.

ServiceLoader and DI frameworks solve similar problems but aren't equivalent technologies. ServiceLoader loads implementations of a particular interface found in the classpath. For example if you have a program which reads Excel spreadsheets and you find a reader capable of reading CSV files (that implements the same interface), you can drop the reader into the classpath and make it available and selectable as an option within your program. (This means that your code is inherently more flexible).

Dependency Injection (at least in terms of Spring) requires apriori knowledge of the classes found in it's classpath in order to inject it. Your Spring config files need to be modified in order to take advantage of any additional implementations that you add to the classpath. It can't simply pick them by restarting the server.

ServiceLoader is less general than a full dependency injection framework like Spring or Guice. It is designed to lazily load services, that can be deployed at run-time. Therefore ServiceLoader is especially useful for plugins.

For a complete answer you must ask to Tom Hawtin Tackline .

Ignoring various performance complaints and class loader issues the real architecture issue with the ServiceLoader is that basically degenerates into the Service locator pattern and all the general problems that come with the service locator pattern (static initializers). Consequently there are some that believe the service locator pattern is evil and better to use full DI or plugin framework especially since @Inject is now standardized.

Thus some alternatives are:

sun.misc.Service

http://www.docjar.com/docs/api/sun/misc/Service.html

Beware, it is not a part of standard J2SE API! It is non-standard part of Sun JDK. So you can not rely on it if you use, say, JRockit.

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