Skip to main content

Custom components

The Genesis Application Platform enables you to create modules for business logic.

Injecting dependencies​

A key part of writing custom code is injecting the objects which your module or process relies on.

Genesis supports some of the key annotations from jakarta.annotation and jakarta.inject, defined in Jakarta EE, using Google Guice as the internal dependency injection mechanism. In addition, Genesis provides some of its own annotations.

@Module​

All classes that need to be created on microservice start-up must be annotated with @Module. This ensures the instance is created as singleton.

The class's package must also be in the <package> list of the process that should create it in your *-processes.xml file; a process only creates @Module classes from the packages it scans. See the package tag.

@ProviderOf​

This is used to annotate a class that is responsible for acting as Factory for a specified type. Adding the @Singleton annotation ensures that only one Factory class is created.

Example:

@Singleton
@ProviderOf(type = PriceFeed::class)
class PriceFeedProvider : Provider<PriceFeed> {
override fun get(): PriceFeed {
return PriceFeed()
}
}

@Inject​

This is used to annotate a field or constructor to indicate to Genesis that it should inject an object of matching type during the dependency injection stage. These types can be provided with the aforementioned @Module and @ProviderOf annotations. You should use the Jakarta @Inject annotation (jakarta.inject.Inject) for best practice.

@Named​

This annotation is used to provide Genesis system definition properties as part of the dependency injection mechanism, and should be used alongside @Inject.

@PostConstruct​

Genesis calls a method annotated with @PostConstruct once, synchronously, as soon as the object has been created and its dependencies injected. Singletons are created when the process starts, so their @PostConstruct methods run during start-up. If the method throws, the object isn't created: Guice reports a ProvisionException and the process fails to start, instead of running on with a half-initialised object.

@PreDestroy​

Genesis calls a method annotated with @PreDestroy once, when the process shuts down. Objects are torn down in the reverse of the order they were created, on the shutdown thread, with no time limit per method. If a @PreDestroy method throws, Genesis logs the error and carries on shutting down the remaining objects.

Lifecycle rules​

Both annotations follow these rules:

  • Only jakarta.annotation.PostConstruct and jakarta.annotation.PreDestroy are honoured. A method annotated with the javax.annotation version is never called.
  • The method must be non-static and take no parameters. Genesis logs a warning and skips any other annotated method, including a Kotlin suspend function.
  • Annotated methods inherited from a superclass run too. A superclass's @PostConstruct runs before the subclass's, and its @PreDestroy runs after. Each method runs once per object, even when a subclass overrides an annotated method and annotates it again.
  • Annotations on interface methods, default methods included, are ignored.
  • Objects you bind with toInstance(...) in a Guice module are created by you, not by Genesis, so their lifecycle methods aren't called.

Example​

The example below combines @Module, @Named and @Inject annotations on a constructor and on a field, and it uses @PostConstruct and @PreDestroy.

import global.genesis.commons.annotation.Module
import global.genesis.db.rx.entity.multi.AsyncEntityDb
import jakarta.annotation.PostConstruct
import jakarta.annotation.PreDestroy
import jakarta.inject.Inject
import jakarta.inject.Named
import org.slf4j.LoggerFactory

@Module
class PriceFeed @Inject constructor(@Named("CONNECTION_URL") private val connectionUrl: String) {

private val LOG = LoggerFactory.getLogger(PriceFeed::class.java)

@Inject
private lateinit var entityDb: AsyncEntityDb

@PostConstruct
fun init() {
LOG.info("Starting PriceFeed, connecting to {}", connectionUrl)
}

@PreDestroy
fun cleanUp() {
LOG.info("Stopping PriceFeed")
}
}

CONNECTION_URL must be defined as an item in your system definition, or the process fails to start. See Injectable properties from System Definition.

Conditional annotations​

Conditional on property​

You can define a module as conditional, based on system definition properties. In the example below, the AeronDriverModule will only be instantiated if the MqLayer property is set to AERON:

@Module
@ConditionalOnProperty("MqLayer", conditionalValue = "AERON")

Conditional on class​

Likewise, modules can be defined to be conditional on classes, so if the selected class has been instantiated (e.g. the previous example shown as AeronDriverModule), then our dependency injection mechanism will instantiate this class as well.

@Module
@ConditionalOnClass(AeronDriverModule::class)

Conditional on missing class​

You can also add conditional modules on missing classes. This annotation is very helpful if you want to develop an “extension” mechanism as part of your application.

For example, you could define an interface. You could then define an @Module implementing this interface with a conditional on that interface class being missing.

  • If a class is defined as an @Module that implements the interface, that class will be selected (i.e. this class can be defined in an external jar and added to classpath using framework config).
  • If no class is defined as an @Module to implement that interface, then the @ConditionalOnMissingClass module will be instantiated.

For example, imagine you want to create a “hook” into the Genesis message-handling logic, so it can be extended as desired in other applications. The interface and default class would look like this in Kotlin:

interface MessageTracer{
fun onMessageReceived(msg: Message)
}

@Module
@ConditionalOnMissingClass(MessageTracer::class)
class DefaultMessageTracer : MessageTracer{
override fun onMessageReceived(msg: Message) = println("This is a message $msg")
}

If an application requires custom logic, a new @Module class could be defined in a separate jar file like this:

@Module
class ProductMessageTracer : MessageTracer{
override fun onMessageReceived(msg: Message) = println("Hi $msg")
}

If the package for this class is available in the classpath (<classpath> section in processes.xml) and is also being scanned (i.e. <package> section in processes.xml), ProductMessageTracer will take precedence when starting the process and DefaultMessageTracer will be ignored. Otherwise, DefaultMessageTracer will be instantiated.

Conditional on property and missing class​

Lastly, we have a combination of both “conditional on property” and “conditional on missing class“ annotations. Referring to the previous example, we could use both features at once like this:

@Module
@ConditionalOnPropertyAndMissingClass("MessageTracer", conditionalValue = "DEFAULT", MessageTracer::class)
class DefaultMessageTracer : MessageTracer{
override fun onMessageReceived(msg: Message) = println("This is a message $msg")
}

The process will crash on start up if the system definition value for MessageTracer is set to anything other than DEFAULT and no implementation has been provided for MessageTracer. This annotation can be used to enforce good practice.

Injectable properties from System Definition​

Example of genesis-system-definition.kts file​

systemDefinition {
global {
item(name = "CONFIG_FILE_NAME", value = "/data/")
// other params omitted for simplicity
}
}

System Definition property being referenced in Java file​

@Inject
public RequestReplyDefinitionReader(RxDb db,
@Named("CONFIG_FILE_NAME") String configFileName) throws GenesisConfigurationException {
this(db.getDictionary(), configFileName);
}

Conditional on property and missing class​

Lastly, you can use a combination of both "conditional on property" and "conditional on missing class" annotations. Referring to the previous example, you can use both features at once like this:

@Module
@ConditionalOnPropertyAndMissingClass("MessageTracer", conditionalValue = "DEFAULT", MessageTracer::class)
class DefaultMessageTracer : MessageTracer{
override fun onMessageReceived(msg: Message) = println("This is a message $msg")
}

If the condition fails (for example, if the system definition value for MessageTracer is set to anything other than DEFAULT), the module is not registered. Note that this annotation does not directly cause a start-up failure. Instead, a start-up failure only occurs if another component attempts to @Inject the now-unbound type, resulting in a standard Guice missing-binding error.