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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Develop Event-Driven Architectures
  • Ports and Adapters Architecture with Kafka, Avro, and Spring-Boot
  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus

Trending

  • Understanding IEEE 802.11(Wi-Fi) Encryption and Authentication: Write Your Own Custom Packet Sniffer
  • Agentic AI for Automated Application Security and Vulnerability Management
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • Ethical AI in Agile
  1. DZone
  2. Coding
  3. Java
  4. Hexagonal Architecture for Java

Hexagonal Architecture for Java

Learn more about how you can isolate your core logic from outside elements.

By 
Rajesh Bhojwani user avatar
Rajesh Bhojwani
·
Jan. 03, 19 · Presentation
Likes (14)
Comment
Save
Tweet
Share
41.8K Views

Join the DZone community and get the full member experience.

Join For Free

Hexagonal architecture is a style that talks about layering your objects in a way that isolates your core logic from outside elements. The core logic is the piece specific to your business, and outside elements are like integration points, e.g. DBs, external APIs, UIs, and others. It divides software into the inside and outside parts. Inside parts contain Core Business logic and the Domain layer (explained in LayeredArchitecture). The outside part consists of UI, database, messaging, and other stuff. Inside and Outside parts both communicate with each other via ports and adapters.

Benefits

  • Software developed using this architecture is independent of channels and can support multiple channels
  • Easy to swap out the inbound and outbound integration points
  • Testing the software becomes easy because we can mock integration points easily

Implementation in Java

As explained above, the hexagonal architecture is more around ports and adapters. In Java, interfaces implement the ports and the implementation class works as the adapters. So, we will take a look at a simple example using the Spring Boot application and see how this style can be applied to this app.

In this application, we have the functionality to create/view Employee Details. The Core Business logic is in the EmployeeService and the domain is an Employee. So, these will be considered as inside parts.

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepositoryPort employeeRepository;

    public void create(String name, String role, long salary){
        employeeRepository.create(name, role, salary);
    }

    public Employee view(Integer userId){
        return employeeRepository.getEmployee(userId);
    }
}
@Entity
@Table(name = "employee")
public class Employee{
    @Id
    @GeneratedValue
    @Column(name = "id")
    private Integer id;

    @Column(name = "name", nullable = false)
    private String name;

    @Column(name = "role", nullable = false)
    private String role;

    @Column(name = "salary", nullable = false)
    private long salary;
    // Setter and Getter methods
}


So now, this application can expose this functionality via REST or Messaging. Hence, we have created the EmployeeControllerAdapter to expose REST endpoints, which implements the EmployeeUIPort.

@RestController
@RequestMapping("/employees/")
public class EmployeeControllerAdapter implements EmployeeUIPort{

    @Autowired
    private EmployeeService employeeService;

   @Override
    public void create(@RequestBody Employee request) {
        employeeService.create(request.getName(), request.getRole(), request.getSalary());
    }

    @Override
    public Employee view(@PathVariable Integer id) {
        Employee employee = employeeService.view(id);
        return employee;
    }
}
 public interface EmployeeUIPort {
 @PostMapping("create")
    public void create(@RequestBody Employee request);

    @GetMapping("view/{id}")
    public Employee view(@PathVariable Integer userId);
 }


As part of the business logic, EmployeeService also needs to call the DB, which is, again, an integration point (outside part), so we have created the EmployeeRepositoryPort, andEmployeeServiceAdapterimplements this port.

@Service
public class EmployeeServiceAdapter implements EmployeeRepositoryPort {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional
    @Override
    public void create(String name, String role, long salary) {
        Employee employee = new Employee();
        employee.setName(name);
        employee.setRole(role);
        employee.setSalary(salary);
        entityManager.persist(employee);
    }

    @Override
    public Employee getEmployee(Integer userId) {
        return entityManager.find(Employee.class, userId);
    }
}
public interface EmployeeRepositoryPort {

    void create(String name, String role, long salary);

    Employee getEmployee(Integer userId);
}


So, we see how EmployeeService has used theEmployeeUIPortport to expose its service and  EmployeeRepositoryPort to interact with the DB. Also,  EmployeeControllerAdapter and EmployeeServiceAdapter help to integrate with REST APIs and DB.

Summary

To summarize, the hexagonal architecture is an approach used to divide the application into inside and outside parts. They are connected through ports (exposed by the inside) and adapters (implemented by the outside). So, by applying this approach, the core use case code remains intact and can serve to multiple channels, supporting different protocols. It also helps to make the application tested easily. However, I would suggest not to implement this architecture fully for the whole application but use interfaces and adapters selectively.

As always, the code of all examples above can be found over on GitHub.

Architecture Java (programming language) application

Opinions expressed by DZone contributors are their own.

Related

  • How to Develop Event-Driven Architectures
  • Ports and Adapters Architecture with Kafka, Avro, and Spring-Boot
  • A Systematic Approach for Java Software Upgrades
  • Building a Simple RAG Application With Java and Quarkus

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!