开始使用 HK2 的最简单方法是使用 hk2-inhabitant-generator。
此插件将生成一个META-INF/hk2-locator/default 文件,HK2 将在您调用时使用该文件填充ServiceLocator
ServiceLocatorUtilities.createAndPopulateServiceLocator();
该文件将填充有@Service 注释的服务类。只需将 hk2-inhabitant-generator 插件添加到您的 pom.xml 中
<plugin>
<groupId>org.glassfish.hk2</groupId>
<artifactId>hk2-inhabitant-generator</artifactId>
<version>${hk2.version}</version>
<executions>
<execution>
<goals>
<goal>generate-inhabitants</goal>
</goals>
</execution>
</executions>
</plugin>
还有课程
@Service
public class School {
private final Teacher teacher;
@Inject
public School(Teacher teacher) {
this.teacher = teacher;
}
}
@Service
public class Teacher {
private final String name;
public Teacher(String name) {
this.name = name;
}
public Teacher() {
this(DEFAULT_NAME);
}
}
然后就可以从ServiceLocator获取服务了
public static void main(String... args) {
ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
Teacher t = locator.getService(Teacher.class);
System.out.println(t.getName());
}
完成项目
https://github.com/psamsotha/hk2-getting-started
更新:hk2-metadata-generator
repo 还包括一个分支metadata-generator,它使用hk2-metadata-generator 而不是hk2-inhabitants-generator。两者的区别在于metadata-generator 将在编译期间创建驻留文件。它只需要在编译期间位于类路径上。这可能更自然地使用。您可以将hk2-metadata-generator 包含在maven-compiler-plugin 配置中
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<inherited>true</inherited>
<configuration>
<source>1.8</source>
<target>1.8</target>
<annotationProcessorPaths>
<annotationProcessorPath>
<groupId>org.glassfish.hk2</groupId>
<artifactId>hk2-metadata-generator</artifactId>
<version>${hk2.version}</version>
</annotationProcessorPath>
</annotationProcessorPaths>
</configuration>
</plugin>
另见