简体   繁体   中英

What is ServiceLoader and how is it used?

I came across the documentation of ServiceLoader and am unclear as to what use cases it suits.

When would one use ServiceLoader ?

You use ServiceLoader when you want your program to have a “plugin” functionality. When you want to allow people to customize your application by adding jar files to the classpath which contain implementations of a specific subset of functionality, you can use a ServiceLoader to look for those implementations in the classpath.

ServiceLoader is itself an implementation of the jar SPI specification , which has been around for a long time. (I believe it was introduced in Java 1.3.)

Java SE already uses it for exactly that purpose in a lot of places, including:

Are you familiar with the principle "Inversion of Control" ?

Java implemented it by ServiceLoader . The class is designed to locate implementation classes of an interface on the classpath. You pass in a service interface, you get an implementation(s) of that service.

You might find a good practical example here .


PS: Even though it's an out-of-the-box solution and a quite simple tool, I think it's outdated and not flexible enough compared to the Spring IoC Container and Google Guice.

ServiceLoader is Java's light weight alternative to a full blown IoC container such as Spring, Guice, etc. It has far less bells and whistles than those frameworks, but works well for basic use cases when you just want to find what classes implement an interface.

Most application servers will have some usages of ServiceLoader you can see in practice:

https://github.com/apache/tomee/search?q=ServiceLoader&unscoped_q=ServiceLoader

https://github.com/apache/tomcat/search?q=ServiceLoader&unscoped_q=ServiceLoader

https://github.com/wildfly/wildfly/search?q=ServiceLoader&unscoped_q=ServiceLoader

When I hear something about ServiceLoader , the first thing, which comes to my mind, is JDBC . This technology provides loading JDBC driver classes from a classpath without using Class.forName(Class<?>clazz) .

Also, I am sure there are many examples of using ServiceLoader , beside JDBC

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