背景知识:
SUN公司提出了一个类似于OSGi的模块化系统规范称之为“HK2”。HK2的全称为“Hundred Kilobytes Kernel”,包括Modules Subsytem和Component Model两部分。据称,该内核将在JDK 7中集成,同时,SUN在其开源的GlassFish J2EE应用服务器项目V3版本中将HK2作为其系统内核实现。
协议: https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
我今天向大家介绍一个比较spring更加轻量级的IOC/DI容器框架, 只要有一个maven依赖即可,如下所示:
<dependency>
<groupId>org.glassfish.hk2</groupId>
<artifactId>hk2</artifactId>
<version>2.3.0</version>
</dependency>
这样就可以在使用该框架了。
因为"HK2"框架在国内资料比较紧缺,所以我来做这么个专题来介绍它,希望大家读完这篇文章能够知道它的原理,以及能够马上使用起来,给自已的系统减减肥,大家都知道,spring框架是多么多么的强大啊,但是它的强大之处呢,却更加觉得它的重量了。所以我们可以去掉它的重量,去拥抱"HK2",当然,"HK2"也做了spring,guice等适配。方便开发者可以很快切换过去的。
下面请允许我来介绍它,来自sun 公司 模化化系统将会给我们带来别样的惊喜呢。
为了它demo更加简单,我开始写一个helloworld吧
@Contract
public interface MyService {
public void helloHK2();
}
大家会觉得接口也要使用注解,这很奇怪哦。没关系,后面的专题会给你一一道来。
它的实现类,如下所示:
@Service @Singleton
public class MyServiceImpl implements MyService {
@Override
public void helloHK2() {
Log4jUtil.info("hello hk2");
}
}
两个注解,好像很酷的赶脚。那接下来要如何去使用它呢。
下面是我写单元测试:
public class TestContext {
private ServiceLocator locator;
@Before
public void doBefore() {
locator = ServiceLocatorFactory.getInstance().create("CustomResolverTest");
Populator.populate(locator);
}
@Test
public void testDI(){
MyService myService = locator.getService(MyService.class);
myService.helloHK2();
}
Populator的类,如下所示:
public class Populator {
public static void populate(ServiceLocator locator) {
DynamicConfigurationService dcs = locator.getService(DynamicConfigurationService.class);
DynamicConfiguration config = dcs.createDynamicConfiguration();
// The InjectionResolver we are showcasing
config.bind(BuilderHelper.link(MyServiceImpl.class).
to(MyService.class).
in(Singleton.class.getName()).
build());
// And commit
config.commit();
}
}
下面,可能有童鞋要问, 写一个接口,以及实现类,都要通过
config.bind(BuilderHelper.link(MyServiceImpl.class).
to(MyService.class).
in(Singleton.class.getName()).
build());
绑定,会不会比较麻烦呢,是的,在实际的运用中,肯定是不能这么使用的。我们可以自定义一个扫包程序,去扫描它。
代码如下:
public class TestContext {
private 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();
}
}
@Test
public void testDI(){
MyService myService = locator.getService(MyService.class);
myService.helloHK2();
}
其中HK2RuntimeInitializer是一个自定义类。详细可以查看我的代码附件。
(完), 有机会一起交流“HK2", 这篇文章算一个入门级文章,让大家先用起来。然后再深入学习。
相关学习链接 :
https://hk2.java.net/2.4.0-b09/ (官网)
http://my.oschina.net/pkm2012/blog/96613