Class School,Teacher,Test belong to same package and are files themselves. As we can see in Test file, i am using new to make all the objects but i want to know how to use HK2 to do the same. I know how to do with guice or spring (either by using configuration file or using xml file) but i don't know how to do DI in HK2. I went through this source but not able to do even after reading from there.
public class School
{
public Teacher t;
}
public class Teacher
{
public void intro
{
System.out.println("I am Math Teacher");
}
}
public class Test
{
public static void main(String[] args)
{
School s = new School();
s.t = new Teacher();
s.t.intro();
}
}
It will be of great help if additional information like how to do DI with HK2 using constructor or setter is given.
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());
}
https://github.com/psamsotha/hk2-getting-started
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>