Category: hk2

Vision Statement

Create a very lightweight email micro-service that will be self-contained, easy to deploy and integrate with. Micro-service could not use any out of the box email servers or email as a service solutions.

Use Case

Suppose, you have an application that needs to send user emails to update a forgotten password or to invite new users to the system. The email capability of your application should be designed as a shared component that can be later extended to send text messages. Email templates should be consistent across different applications and maintained in one place. Email server configuration can be complex, so it needs to be isolated and easily reproducible.

Design Considerations

Spring boot or no spring boot, that is the question. For the itzap-message micro-service, I choose Jersey with hk2 as dependency injection framework. It turns out, that it is quite easy to build executable Jar micro-service with embedded Tomcat without spring/spring-boot. As a result, executable Jar is a lot smaller, faster to load, and deploy. Another component of the system is an email server. To solve email server configuration problems I looked for a Docker container that provides an email server. The Docker container that I found was boky/postfix . Now, to build the application, I can use docker-compose to put everything together.

Implementation Details

Jersey, Tomcat, and HK2

To start building micro-service using Jersey, Tomcat, and HK2 drop theses dependencies in your pom.xml file.








Application Class

The main application class looks like this:

public class EmailApplication
  private static final Logger LOGGER = LoggerFactory.getLogger(EmailApplication.class);

  public static void main(String[] args) {
    try {
    } catch (Exception e) {
      LOGGER.error("ITZap Email application failed to run", e);

  private static void start() throws Exception {

    String contextPath = "";
    String appBase = ".";
    String port = System.getenv("PORT");
    if (port == null || port.isEmpty()) {
      port = "8025";

    Tomcat tomcat = new Tomcat();

    Context context = tomcat.addWebapp(contextPath, appBase);

    Tomcat.addServlet(context, "jersey-container-servlet",
                      new ServletContainer(resourceConfig()));
    context.addServletMappingDecoded(UDecoder.URLDecode("/v1/itzap/message/*", Charset.defaultCharset()),

    // initialize Tomcat. (Since version 9.xx need to add tomcat.getConnector() here)

  private static ResourceConfig resourceConfig() {
    return new JerseyConfig();

HK2 Dependency Injection

I drop all factories as static nested classes in one Factories class for convenience.

public final class Factories {
  private static final Config CONFIG = ConfigFactory.load();

  private Factories() {}

  public static class MailServiceFactory extends AbstractFactory<EMailService> {
    public MailServiceFactory() {

    public EMailService provide() {
      return new EMailService(CONFIG);

Put it all together.

public class JerseyConfig extends ResourceConfig {
  JerseyConfig() {

    // register endpoints

    register(new ContainerLifecycleListener()
               public void onStartup(Container container)
                 // access the ServiceLocator here
                 // serviceLocator = container.getApplicationHandler().
                 ServiceLocator serviceLocator = ((ImmediateHk2InjectionManager)container
                 // ... do what you need with ServiceLocator ...

               public void onReload(Container container) {/*...*/}
               public void onShutdown(Container container) {/*...*/}

    register(new AbstractBinder() {
      protected void configure() {
        // hk2 bindings

More Jersey

One of the features of Jersey that I like is @Provider mechanism. Here is an example of how to centralize error handling in the Jersey application.

public class IZapExceptionMapper implements ExceptionMapper<IZapException> {
  public Response toResponse(IZapException e) {
    ErrorResponse response = MapperUtils.toReturn(e);

    return Response.status(response.getStatus())

Not shown here, but Jersey can actually inject beans into @Provider classes.


I think one of the undervalued configuration/properties management libraries is com.typesafe I like this library for the ease of use, handling property hierarchies, flexibility, and out of the box property loading convention.

private static final Config CONFIG = ConfigFactory.load();
// do some stuff
String emailFrom = CONFIG.getString("email.from");


Some manual work needs to be done to package an application into a single executable Jar. Take a look at the following maven plugin:

      <id>make-assembly</id> <!-- this is used for inheritance merges -->
      <phase>package</phase> <!-- bind to the packaging phase -->

This plugin is using itzap-message.xml descriptor file

<assembly xmlns=""



I usually, unpack all dependencies and merge them into a final jar. There are other strategies for building executable Jar that can be configured in the descriptor file.


I already mentioned adocker-compose as a mechanism for running itzap-message micro-service. Here is an example of the docker-compose.yml

version: '3.2'


    image: boky/postfix

      - 1587:587

    # Builds message service
    build: "."
    image: message-service:latest

      MAIL_HOST: mail
    privileged: true
      - 8025:8025
      - mail

      - mail

Here, you can see two containers mail and message. Mail container comes straight from the Docker Hub boky/postfix while message is a simple java contaner defined in the following Dockerfile

# Alpine Linux with OpenJDK JRE
FROM openjdk:8-jre-alpine
COPY message-impl/target/message-impl-0.0.1-SNAPSHOT.jar /opt/lib/
ENTRYPOINT ["/usr/bin/java"]
CMD ["-jar", "/opt/lib/message-impl-0.0.1-SNAPSHOT.jar"]


itzap-message micro-service application contains two modules: message-api and message-impl. Assuming application consuming itzap-message micro-service is a Java application, having message-api jar streamlines the development of the Java client. API library provides common POJOs and a service interface that can be implemented on the client-side.



itzap-message micro-service project designed to send email messages. Visit my ITZap blog to read more about this project.


itzap-message desinged to run in a Docker container along with postfix that is also running in a Docker. Using docker-compose itzap-message can be deployed anyware and ready to send emails.

How To Build

  • Clone the following projects:
    • git clone
    • git clone
    • git clone
    • git clone
  • Build all projects
    • cd itzap-parent && mvn clean install
    • cd ../itzap-common && mvn clean install
    • cd ../itzap-rxjava && mvn clean install
    • cd ../itzap-message && mvn clean install
  • Running
    • Before running set environment variables export MAIL_FROM = to whater email address will be used to send messages from and export domain used to send emails.
    • To run the itzap-message micro-service docker-compose up
  • Testing
    • Once both Docker containers are running open Postman and call micro-service API to send an email POST http://localhost:8025/v1/itzap/message/email Body
     		"messageId": "new-user",
     		"subject": "test",
     		"addresses": [""],
     		"transport": "email"