The easiest way to get started with HK2 is to use the hk2-inhabitant-generator
.
This plugin will generate a META-INF/hk2-locator/default
file which HK2 will use to populate the ServiceLocator
when you call
ServiceLocatorUtilities.createAndPopulateServiceLocator();
The file gets populated with the service classes annotated with @Service
. Just add the hk2-inhabitant-generator
plugin to your 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>
And the classes
@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);
}
}
Then you can get the service from the ServiceLocator
public static void main(String... args) {
ServiceLocator locator = ServiceLocatorUtilities.createAndPopulateServiceLocator();
Teacher t = locator.getService(Teacher.class);
System.out.println(t.getName());
}
Complete project
https://github.com/psamsotha/hk2-getting-started
Update: hk2-metadata-generator
The repo also includes a branch metadata-generator
that makes use of the hk2-metadata-generator
instead of the hk2-inhabitants-generator
. The difference between the two is that the metadata-generator
will create the inhabitants files during compilation. All it requires is to be on the classpath during compilation. This might be more natural to use. You can include the hk2-metadata-generator
inside the maven-compiler-plugin
configuration
<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>
See also