DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Software Design and Architecture
  3. Microservices
  4. Dependency Inversion 2.0: Enhanced Event-driven Service Design With the magic4j-cdi-utils

Dependency Inversion 2.0: Enhanced Event-driven Service Design With the magic4j-cdi-utils

Learn about dependency inversion, from an EESD quickstart to design considerations.

Stephan Bauer user avatar by
Stephan Bauer
·
Mar. 31, 16 · Tutorial
Like (7)
Save
Tweet
Share
8.81K Views

Join the DZone community and get the full member experience.

Join For Free

have you ever done the design of a layered application – usually representing a certain functional domain or microservice – consisting of the usual web-, façade-, businesslogic- and data-access-layers? did that annoy you because of the continuously rising quantity of pure delegation methods in the façade- and businesslogic-layer that produce nothing but “hot air” (and of course work overhead)? then the cdi-based “enhanced eventdriven service-design” (“eesd”) is for you!

note: although this article explains some basics about cdi-events, it is not a tutorial for newbies. it is presumed, that you already have basic knowledge about cdi and its event mechanism.

eesd-quickstart for java ee designers/developers and architects

the main achievement of eesd – provided by the “magic4j-cdi-utils” library – is, that it enhances the cdi-event mechanism by injecting the result of an event-observer method back into the event-producer – while still keeping both the event-producer and the observer completely decoupled. this seemingly small feature nevertheless opens up the door to a significantly more lightweight application design: in a traditional layered application design that conforms to the dependency inversion principle (dip), you needed interface methods in api-modules of each layer as the abstraction from higher-level- to lower-level-modules (see diagram 1 below).

traditional domainlayers with dependency inversion principle

traditional application layers with consideration of the “dependency inversion principle”

in eesd, cdi-events replace these api-methods as the abstraction. an interceptor provided by the magic4j-cdi-utils delivers the ability to inject return values into the event-producer. crud-methods which do not need additional business logic are ideal eesd-usecases: just imagine that you can now trigger a dao-method from the web-layer without the need to go through the facade- and businesslogic-layers. instead of bloating the intermediate interfaces and implementation classes with useless methods, you only involve those modules that really contribute to the solution.

in order to round up this quick intro, here are example code snippets that show you the implementation of eesd with magic4j. if you are familiar with cdi and its event-mechanism, you will probably already be able to look through its easy usage. the central part of magic4j-cdi-utils is the “eventresultproviderinterceptor” that manages the provision of the result value to the event-producer. be aware, that there is no need to fire back a second cdi-event to the original event-producer!

@eventresultreceiver
@requestscoped
@path("v1/orders")
public class ordersresource {

    @inject
    private jaxbxmlconverter jaxbxmlconverter;

    @inject
    @retrieveorder
    private event retrieveorderbyidevent;

    @retrieveorder
    private string retrievedorderasxml;

    /**
     * retrieves representation of an instance of
     * me.stephanbauer.eventdriven.microservice.web.ordersresource
     *
     * @param orderid
     * @return an instance of
     * me.stephanbauer.eventdriven.microservice.core.orderdto
     */
    @get
    @produces("application/xml")
    @path("{orderid}/")
    public orderdto getorderbyid(@pathparam("orderid") long orderid) {
        retrieveorderbyidevent.fire(orderid);
        orderdto orderdto = this.jaxbxmlconverter.unmarshallxml(retrievedorderasxml, orderdto.class);
        return orderdto;
    }
}

listing1: the rest-service produces the @retrieveorderbyid event.

please look at the following annotations here:

  • the @eventresultreceiver annotation at class level: this is needed so that the magic4j-interceptor can find the desired result value injection point quicker, as it only needs to search through beans that have this particular annotation.

  • the custom @retrieveorderevent annotation, which is a usecase-specific cdi-qualifier, that the developer needs to provide. in the event-producer, there are two places, where this annotation is needed: the event itself and the instance variable, into which the return value should get injected.

please also note, that the event-producer must be an @requestscoped cdi-bean. i’ll explain this in a minute.

below you find the code snippet for the observer-bean.

@requestscoped
@eventresultreceiver
public class orderdaoimpl {

    @inject
    @maporderentitytodto
    private event maporderentitytodtoevent;

    @maporderentitytodto
    private string orderdtoasxml;

    @eventresultprovider
    public string retrieveorderbyid(@observes @retrieveorder long orderid) {
        orderentity orderentity = new orderentity();
        orderentity.setid(orderid);
        orderentity.setordernumber("123");
        orderentity.setamount(bigdecimal.ten);
        maporderentitytodtoevent.fire(orderentity);
        return this.orderdtoasxml;
    }
}

listing 2: the bean with the observer-method for the @retrieveorder event.

please look at the following annotations here:

  • the observer-method (the one with the @observes -annotation) is annotated with @eventresultprovider , which is the interceptor-annotation for activating the magic4j-eventresultproviderinterceptor. this interceptor actually performs the return value injection into the event-producer by looking for a bean with the corresponding return value injection point (see listing 1).

  • this bean is also annotated with @eventresultreceiver , because in this example, the retrieveorderbyid()-method also uses eesd for triggering the mapping from the orderentity instance to the orderdto-instance. you may wonder, why this method returns the orderdto as a string. this is because of the fact, that i didn’t want to introduce additional dependencies upon the dto-module in the dao-module just because of eesd. you’ll find more details on this in the next chapter.
  • please be also aware, that this observer-method does not return void, as it is done by usual observer-methods. instead, it returns the value to be injected into the event-producer. the interceptor is the one, who receives this return value and performs the injection.

the call sequence of the retrieveorderbyid(orderid) example

as already mentioned above, there are 3 beans and 2 events involved in this example:

  • the restful webservice “ordersresource”
  • the orderdaoimpl bean
  • the dtomapperimpl bean for mapping from entity to dto

the following activity-diagram should clear up the call sequence:

eesd-retrieveorderactivity

activity-diagram of the retrieveorderbyid()-example

the six eesd-key design considerations

1. independent components without vertical hierarchy

in eesd, the layers lose their aspect of being at a fix, certain level in the hierarchy of layers, where each layer has to be called by its superior layer in every request.

    • instead, each layer is considered as an independent component, to which no other component needs a compile-time dependency. you can consider all components being on the same hierarchy level, it’s just that each component has its well-defined and cleanly separated responsibility.

    • thus, the name “layer” is not suitable for eesd anymore. each component can fire events that get serviced in any of the other components. the event-producer doesn’t (need to) know which component provides the corresponding observer-method.

2. predictable execution order through synchronous event delivery

due to the synchronous nature of the cdi-event delivery (default behavior), the execution sequence is exactly predefined. in fact, the method that fires an event receives back the flow control only after the event has been completely processed by the observer-method (and the result has been injected into it by magic4j). furthermore, it is also possible to nest events in that sense, that you can fire another event from within an observer-method. see the above activity-diagram for a concrete call sequence with 3 components and 2 events:

3. observer-method-result injection

by applying the eventresultproviderinterceptor and some more annotations from the “magic4j-cdi-utils” library, the result from the observer-logic gets automatically injected into the event-producer-bean. this leads to a situation where you can effectively mimic a normal call to a non-void method without any coupling between the caller and the callee. in other words, you call a method indirectly and the assignment of the result variable happens under the covers of magic4j.

4. @requestsoped event-producer-beans for threadsafe instance variable value injection

each event-producer bean that is meant to receive a return a value from an observer, must be an @requestscoped cdi-bean. the main reason for this is, that magic4j can provide the return value only to an instance variable of the event-producer. if the scope was for example @applicationscoped, then mutable instance variables lead to thread-unsafety. as of magic4j version 1.0, each bean with an observer-method that is meant to return a value to the event-producer, must also be @requestscoped .

5. effects of skipping the facade

the façade-component is no longer needed for eesd-usecases. thus the two main responsibilities of the traditional façade get split up into other components:

  • the dto-to-entity-mapping (and vice-versa) gets separated out into a dedicated mapping component without any other responsibility.

  • the second traditional façade-responsibility is the transaction handling.

5.1 modificated dto-mapping for keeping dependencies clean

in order to keep the module dependencies to the dto-api- and the entity-api-module clean, the dto-to-entity-mapper-component must provide map-methods that return the target-instance as a serialized xml- or json-string. the reason for this is, that by dissolving the façade-component we lost exactly that one component that was the only one to have dependencies to both modules. nevertheless, we still want the web-component to only depend on the dtos while the business-services and the daos should still only depend on the entities.

the mapping from the entity to the dto must now be initiated by the dao- or businessservice-component. in order to avoid a dependency to the dto-module there, the mapper cannot return the dto itself, but instead a serialized xml- or json-string representation of it.

the same is valid vice versa for the web-component when it needs to transform the dto to an entity. but this is no problem for the dtos because they need to be xml/json-serializable anyway so that jax-rs can send them over the wire. the only overhead is, that you need to make the entities xml/json-serializable as well.

5.2 shifting the transaction boundary into the weblayer

in the absence of the façade-layer, the transaction boundary gets shifted into the web-layer. therefore, there are at least the following two alternatives:

  • if you have ejbs and want them to take care of the transaction-boundary, then you can define the jax-rs-resource class as a stateless session ejb: but ejbs currently cannot send cdi-events, so the ejb must delegate the request to an @requestscoped-cdi-bean, which in turn represents the starting point of the event-driven call flow.
  • if you don’t want or cannot have ejbs, you can either start a usertransaction manually or you integrate a cdi-extension like apache deltaspike and let it demarcate the transaction-boundary for you. in that case, the jax-rs resource-bean can itself be an @requestscoped cdi-bean and so you can get along with only one bean if you like.

testing

although there are frameworks like apache delta spike, that make it possible to unittest cdi-injections in a standard-unittest-vm, testing eesd-interactions outside of a jee container currently seems to be impossible, because @requestscoped beans do not seem to be supported in standard-vms (see the list of supported features of weld 2.3.3 final )

note: although the author is not a fan of the arquilian framework, this currently seems to be the only way to write tests for eesd. please leave a comment if you know about alternative test possibilities. anyway i have of course done integration testing including load testing in order to ensure, that return values don’t get mixed up because of multi-threading issues.

final recommendations for eesd

the question arises, if you should completely set aside the api-modules, especially also for those cases, where each layer does contribute to the solution. to be honest, i think that in such cases, you should still prefer the usual programming model, because it’s easier to read.

for crud-operations where no additional code in the business logic component is needed, you receive the full benefits of eesd.

even if you need some business logic, you can still skip the facade. the event fired from the web-component gets observed in the business logic component and from there, the dao-method should be called via a normal api-interface method.

to generalize this: if you need to communicate between 2 components that were direct neighbours in the traditional application layer concept, then you should stick to the traditional direct method calls, because it keeps your code more readable. as soon as you can skip one layer, you should use eesd. i want to discourage you from introducing additional dependencies compared to the traditional layering, e.g. the weblayer should not get a compile dependency to the business logic api or the dao-api.

thus the best approach for readability on the one hand and code compactness on the other hand should be to use both design strategies in parallel and use the best of both worlds where appropriate.

downloading magic4j-cdi-utils

i have released the magic4j-cdi-utils under the apache license 2.0 to the central maven repository. thus you simply need to add the following maven dependency:

<dependency>
<groupid>org.magic4j</groupid>
<artifactid>magic4j-cdi-utils</artifactid>
<version>1.0.0.0</version>
</dependency>
Dependency Design Service design Event Business logic Bean (software) Spring Framework application Annotation microservice Instance variable

Published at DZone with permission of Stephan Bauer, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Apache Kafka Is NOT Real Real-Time Data Streaming!
  • Cucumber.js Tutorial With Examples For Selenium JavaScript
  • GitLab vs Jenkins: Which Is the Best CI/CD Tool?
  • Practical Example of Using CSS Layer

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: