1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/samples/componentinjection/src/org/apidesign/component/InjectionViaServiceLoader.java Sat Jun 14 09:53:44 2008 +0200
1.3 @@ -0,0 +1,22 @@
1.4 +package org.apidesign.component;
1.5 +
1.6 +import java.util.Collection;
1.7 +import java.util.ServiceLoader;
1.8 +import org.openide.util.Lookup;
1.9 +
1.10 +public class InjectionViaServiceLoader {
1.11 + private InjectionViaServiceLoader() {
1.12 + }
1.13 +
1.14 + // BEGIN: lookup.query.serviceloader
1.15 + public static InjectionSlot singleSlot() {
1.16 + // get one implementation
1.17 + return ServiceLoader.load(InjectionSlot.class).iterator().next();
1.18 + }
1.19 +
1.20 + public static Iterable<? extends InjectionSlot> multiSlot() {
1.21 + // get all registered implementations
1.22 + return ServiceLoader.load(InjectionSlot.class);
1.23 + }
1.24 + // END: lookup.query.serviceloader
1.25 +}
2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/samples/componentinjection/test/org/apidesign/component/InjectionViaServiceLoaderTest.java Sat Jun 14 09:53:44 2008 +0200
2.3 @@ -0,0 +1,46 @@
2.4 +package org.apidesign.component;
2.5 +
2.6 +import java.util.Iterator;
2.7 +import org.junit.BeforeClass;
2.8 +import org.junit.Test;
2.9 +import org.netbeans.junit.MockServices;
2.10 +import static org.junit.Assert.*;
2.11 +
2.12 +// BEGIN: lookup.mockservices.serviceloader
2.13 +public class InjectionViaServiceLoaderTest {
2.14 + public InjectionViaServiceLoaderTest() {
2.15 + }
2.16 +
2.17 + @BeforeClass
2.18 + public static void setUpClass() throws Exception {
2.19 + // this is a support for "dynamic" registration of any class
2.20 + // into the global pool of Lookup.getDefault() and java.util.ServiceLoader
2.21 + // either in @BeforeClass or @Before register
2.22 + // classes of the mock instances that you want your code
2.23 + // to find
2.24 + MockServices.setServices(ImplOne.class, ImplTwo.class);
2.25 + }
2.26 +
2.27 + @Test
2.28 + public void singleSlot() {
2.29 + InjectionSlot result = InjectionViaServiceLoader.singleSlot();
2.30 + assertNotNull("Some result found", result);
2.31 + assertEquals("The first is ImplOne", ImplOne.class, result.getClass());
2.32 + }
2.33 +
2.34 + @Test
2.35 + public void multiSlot() {
2.36 + Iterator<? extends InjectionSlot> it = InjectionViaServiceLoader.multiSlot().iterator();
2.37 + assertTrue("Has at least one", it.hasNext());
2.38 + assertEquals("The first is ImplOne", ImplOne.class, it.next().getClass());
2.39 + assertTrue("Has two", it.hasNext());
2.40 + assertEquals("The second is ImplTwo", ImplTwo.class, it.next().getClass());
2.41 + assertFalse("No other instance registered", it.hasNext());
2.42 + }
2.43 +
2.44 + public static final class ImplOne extends InjectionSlot {
2.45 + }
2.46 + public static final class ImplTwo extends InjectionSlot {
2.47 + }
2.48 +}
2.49 +// BEGIN: lookup.mockservices.serviceloader