# HG changeset patch # User Jaroslav Tulach # Date 1213430024 -7200 # Node ID ab11b91730892e7ee029ee50164f4eb69b76797e # Parent d098b8e4de15892ea3ff6d01cd5802aeb57bdbbd Showing use of service loader diff -r d098b8e4de15 -r ab11b9173089 samples/componentinjection/src/org/apidesign/component/InjectionViaServiceLoader.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/componentinjection/src/org/apidesign/component/InjectionViaServiceLoader.java Sat Jun 14 09:53:44 2008 +0200 @@ -0,0 +1,22 @@ +package org.apidesign.component; + +import java.util.Collection; +import java.util.ServiceLoader; +import org.openide.util.Lookup; + +public class InjectionViaServiceLoader { + private InjectionViaServiceLoader() { + } + + // BEGIN: lookup.query.serviceloader + public static InjectionSlot singleSlot() { + // get one implementation + return ServiceLoader.load(InjectionSlot.class).iterator().next(); + } + + public static Iterable multiSlot() { + // get all registered implementations + return ServiceLoader.load(InjectionSlot.class); + } + // END: lookup.query.serviceloader +} diff -r d098b8e4de15 -r ab11b9173089 samples/componentinjection/test/org/apidesign/component/InjectionViaServiceLoaderTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/samples/componentinjection/test/org/apidesign/component/InjectionViaServiceLoaderTest.java Sat Jun 14 09:53:44 2008 +0200 @@ -0,0 +1,46 @@ +package org.apidesign.component; + +import java.util.Iterator; +import org.junit.BeforeClass; +import org.junit.Test; +import org.netbeans.junit.MockServices; +import static org.junit.Assert.*; + +// BEGIN: lookup.mockservices.serviceloader +public class InjectionViaServiceLoaderTest { + public InjectionViaServiceLoaderTest() { + } + + @BeforeClass + public static void setUpClass() throws Exception { + // this is a support for "dynamic" registration of any class + // into the global pool of Lookup.getDefault() and java.util.ServiceLoader + // either in @BeforeClass or @Before register + // classes of the mock instances that you want your code + // to find + MockServices.setServices(ImplOne.class, ImplTwo.class); + } + + @Test + public void singleSlot() { + InjectionSlot result = InjectionViaServiceLoader.singleSlot(); + assertNotNull("Some result found", result); + assertEquals("The first is ImplOne", ImplOne.class, result.getClass()); + } + + @Test + public void multiSlot() { + Iterator it = InjectionViaServiceLoader.multiSlot().iterator(); + assertTrue("Has at least one", it.hasNext()); + assertEquals("The first is ImplOne", ImplOne.class, it.next().getClass()); + assertTrue("Has two", it.hasNext()); + assertEquals("The second is ImplTwo", ImplTwo.class, it.next().getClass()); + assertFalse("No other instance registered", it.hasNext()); + } + + public static final class ImplOne extends InjectionSlot { + } + public static final class ImplTwo extends InjectionSlot { + } +} +// BEGIN: lookup.mockservices.serviceloader