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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Java Module Benefits With Example
  • Application Mapping: 5 Key Benefits for Software Projects
  • Providing Enum Consistency Between Application and Data

Trending

  • Your API Authentication Isn’t Broken; It’s Quietly Failing in These 6 Ways
  • Building Production-Grade GenAI on GCP with Vertex AI Agent Builder
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • What Is Plagiarism? How to Avoid It and Cite Sources
  1. DZone
  2. Data Engineering
  3. Databases
  4. Hexagonal Architecture in Java

Hexagonal Architecture in Java

By 
Ravi Sharma user avatar
Ravi Sharma
·
Apr. 01, 20 · Tutorial
Likes (19)
Comment
Save
Tweet
Share
21.8K Views

Join the DZone community and get the full member experience.

Join For Free

Overview 

Hexagonal Architecture is a software architecture that allows an application to be equally driven by users, programs, automated tests, or batch scripts and to be developed in isolation from its run-time target system. The intent is to create an application to work without either a User Interface or a database so that we can run an automated regression test against the application, work with an application when a run-time system, such as a database is not available, or integrate applications without user interface.

Motivation

Many applications have two ends: a user-side and server-side, often designed in two, three, or n-layers architecture. The main problem with n-layered architecture is the layer lines are not taken seriously, causing application logic to leaks across the boundaries. This entanglement between the business logic and the interaction makes it impossible or difficult to extend or maintain the application. 

For instance, adding a new attractive UI to support new devices could be a tough task when the application business logic is not completely isolated in its own boundary. In addition, applications can have more than two sides that make it more difficult to fit well in one-dimensional layer architecture, as shown below.

Three-Layer vs Hexagonal architecture

The hexagonal, or ports and adapters or onion architecture, solves these problems. In this architecture, the application in the inside communications over some number of ports with systems on the outside. Here, the term hexagonal itself is not important, rather it demonstrates the effect to insert ports and adapters as needed in the application in a uniform and symmetric way. The main idea is to isolate the application domain by using ports and adapters.

Organizing Code Around Ports and Adapters

Let's build a small anagram application to show how to organize code around ports and adapters to represents the interaction between inside and outside the application. On the left, we have an application, such as console or REST and inside is the core business logic or domain. The anagram service takes two Strings and returns a Boolean corresponding to whether or not the two String arguments are anagrams of each other. On the right, we have the server-side or infrastructure, for instance, a database for logging metrics about service usage.

Anagram application architecture

The Anagram application source code below shows how the core domain is isolated inside and ports and adapters are provided to interact with it.

Domain Layer

The domain layer represents the inside of the application and provides ports to interact with application use cases.

  • IAnagramServicePort interface defines a single method that takes two String words and returns a boolean.
  • AnagramService implements the IAnagramServicePort interface and provides business logic to determine whether or not the two String arguments are anagram. It also uses the IAnagramMetricPort to output the service usage metric to server-side run-time outside entities such as a database.

Application Layer

The application layer provides different adapters for outside entities to interact with the domain. The interaction dependency goes inside.

  • ConsoleAnagramAdaptor uses the IAnagramServicePort to interact with the domain inside the application.
  • AnagramsController also uses the IAnagramServicePort to interact with the domain. Similarly, we can write many more adaptors to allow various outside entities to interact with the application domain.

Infrastructure Layer

Provide adapters and server-side logic to interact with the application from the right side. Server-side entities, such as a database or other run-time devices, use these adapters to interact with the domain. Note the interaction dependency goes inside.

Outside Entities Interacting With the Application

The following two outside entities use adapters to interact with the application domain. As we can see, the application domain is completely isolated and equally driven by them regardless of external technology.

Here's a simple console application interacting with the application domain using an adapter:

Java
 
x
 
1
    @Configuration
2
    public class AnagramConsoleApplication {
3
  
4
        @Autowired
5
        private ConsoleAnagramAdapter anagramAdapter;
6
    
7
        public static void main(String[] args) {
8
            Scanner scanner = new Scanner(System.in);
9
            String word1 = scanner.next();
10
            String word2 = scanner.next();
11
            boolean isAnagram = anagramAdapter.isAnagram(word1, word2);
12
            if (isAnagram) {
13
                System.out.println("Words are anagram.");
14
            } else {
15
                System.out.println("Words are not anagram.");
16
            }
17
        }
18
    }


Here's an example of a simple test script mocking the user interaction with the application domain using a REST adapter.

Java
x
 
1
    @SpringBootTest
2
    @AutoConfigureMockMvc
3
    public class AnagramsControllerTest {
4
    
5
        private static final String URL_PREFIX = "/anagrams/";
6
    
7
        @Autowired
8
        private MockMvc mockMvc;
9
    
10
        @Test
11
        public void whenWordsAreAnagrams_thenIsOK() throws Exception {
12
            String url = URL_PREFIX + "/Hello/hello";
13
         this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isOk())
14
            .andExpect(content().string(containsString("{\"areAnagrams\":true}")));
15
        }
16
    
17
        @Test
18
        public void whenWordsAreNotAnagrams_thenIsOK() throws Exception {
19
            String url = URL_PREFIX + "/HelloDAD/HelloMOM";
20
            this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isOk())
21
             .andExpect(content().string(containsString("{\"areAnagrams\":false}")));
22
        }
23
    
24
25
        @Test
26
        public void whenFirstPathVariableConstraintViolation_thenBadRequest() throws Exception {
27
            String url = URL_PREFIX + "/11/string";
28
            this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isBadRequest()).andExpect(
29
                    content().string(containsString("string1")));
30
        }
31
    
32
        @Test
33
        public void whenSecondPathVariableConstraintViolation_thenBadRequest() throws Exception {
34
            String url = URL_PREFIX + "/string/11";
35
            this.mockMvc.perform(get(url)).andDo(print()).andExpect(status().isBadRequest()).andExpect(
36
                    content().string(containsString("string2")));
37
        }
38
}
39


Conclusion

Using ports and adapters, the application domain is isolated at the inner hexagon, and it can be equally driven by a user or automated test scripts regardless of the external system or technology.

application Software architecture Database Application domain Java (programming language) Business logic

Opinions expressed by DZone contributors are their own.

Related

  • Finally, an ORM That Matches Modern Architectural Patterns!
  • Java Module Benefits With Example
  • Application Mapping: 5 Key Benefits for Software Projects
  • Providing Enum Consistency Between Application and Data

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook