相信大家也看到HK2过官方的例子,如果没有看的话,我帖出地址:https://hk2.java.net/2.4.0-b09/introduction.html
不过官方的讲解有点儿不太完整,所以我下面扩展下供大家参考和使用。从而能明白了解,以及快速上手。
首先一个简单的例子调用:
@Contract public interface Foo { }
实现类如下所示:
@Service public class FooImpl implements Foo{ @Inject @Named("MobyDick") private Book mobyDick; @PostConstruct private void postConstruct() { mobyDick.doSomething(); } }
里面用到的Book以及它的实现类如下所示:
@Contract public interface Book { void doSomething(); }
@Service @Named public class MobyDick implements Book{ @Override public void doSomething() { Log4jUtil.info("hello Moby Dick"); } }
@Service @Named public class ParadiseLost implements Book { @Override public void doSomething() { Log4jUtil.info("Hello Paradise lost!"); } }
注意: Book类有两个实现类, 它是通过@Name来做区分的哦。
单元测试如下:
@Test public void testDI2() { Foo foo = locator.getService(Foo.class); }
下面再举一个例子,稍微麻烦一点,它是通过自定义注解来区别的:
首先定义下三个注解:
@Qualifier @Retention(RUNTIME) @Target({ TYPE, METHOD, FIELD,PARAMETER }) public @interface Blue { }
@Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) public @interface Red { }
@Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER }) public @interface Yellow { }
下面是调用它的实现类, 如下所示:
@Service public class ColorMixer2 { @Inject @Red private Provider<Color> redProvider; @Inject @Blue private Provider<Color> blueProvider; @Inject @Yellow private Provider<Color> yellowProvider; public Color makePurple() { return mix(redProvider.get(), blueProvider.get(), yellowProvider.get()); } private Color mix(Color color, Color color1, Color color2) { Random random = new Random(); //1~4之间的整形数字 int valueNum = 1 + random.nextInt(3); Color tempColor = null; switch (valueNum){ case 1: tempColor = color; break; case 2: tempColor = color1; break; case 3: tempColor = color2; break; default: tempColor = color; } return tempColor; } }
我们可以看到@Red ,@Yellow等自定义注解,并通过Provider<T>来配合使用,而通过 provider对象的get()方法即可获得当前值。mix是我突发想象写出来的,大家可以参考之。以下是单元测试,如下所示:
@Test public void testMix(){ ColorMixer2 colorMixer2 = locator.getService(ColorMixer2.class); for(int i = 0 ; i < 10; i++) { Color color = colorMixer2.makePurple(); color.print(); } }
想必大家会问locator在哪里初始化呢,别急,在这里我附上测试基类。
public class BaseTest { public ServiceLocator locator; @Before public void doBefore() { try { locator = HK2RuntimeInitializer.init("SceneDev-HK-Locator", false, "com.gzisming.hk2.service.impl"); //full search //ServiceLocator foo = HK2RuntimeInitializer.init("OtherName", false); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } }
(完,待续.......)