So far you have seen how to organize our code into layers so that we can avoid tight coupling between codes and improve reusability and separation of concerns. We just created one domain class, one repository class, and one service class to demonstrate a purpose, but a typical real-world MVC application may contain many domain, repository, and service classes. Each layer is usually connected through interfaces, and the controller always accesses domain objects from the repository via a service interface only.
So every typical enterprise-level Spring MVC application will logically have four layers, namely Presentation, Domain, Persistence, and Services. The Domain layer is sometimes called the model layer. The following block diagram will help you conceptualize this idea:
So you have learned how to create a Service layer object and a repository layer object, but what you saw in the Service layer and repository layer was just a glimpse. Spring has extensive support for database and transaction handling, which is a vast topic and deserves its own book. So in the upcoming chapters, we will concentrate more on the Presentation layer, which contains more Spring MVC related concepts, rather than the database and transaction-related concepts.
It's great that we have listed all our products in our web application under the URL http://localhost:8080/webstore/products
, but in order to become a successful web store, maintaining only the product information is not enough-we need to maintain information about the customers as well, so that we can attract them by giving them special discounts based on their purchase history.
So why don't you maintain customer information in your application too? Here are some improvements you can make to your application to maintain customer information as well as product information:
Customer
domain class in the same package where Product
exists:customerId
, name
, address
, and noOfOrdersMade
to the Customer
classCustomerRepository
with a method declaration such as List <Customers> getAllCustomers()
InMemoryCustomerRepository
implementation for CustomerRepository
and instantiate some dummy customer in the constructor of InMemoryCustomerRepository
likes we did in InMemoryProductRepository
CustomerService
with a method declaration such as List <Customers> getAllCustomers()
CustomerServiceImpl
for CustomerService
CustomerController
http://localhost:8080/webstore/customers
customers.jsp
After finishing this exercise, you will be able to see all your customers under the URL http://localhost:8080/webstore/customers
. It is very similar to the way we listed all our products under the URL http://localhost:8080/webstore/products
.