Skip to lesson

Package by layer vs package by feature

ShopLite now has product, category, customer and order code. If one folder holds every controller and another every service, a change to products touches five folders, and any class can call any other.

Package by layer: controller, service, repository folders

Package by layer groups classes by technical job: all controllers in one package, all services in another, all repositories in a third, plus model and dto packages.

Here is ShopLite packaged by layer. Count the folders that one product change would touch.

Example 1 · The same app, packaged by layer

Runs in: a copy of shoplite-api with the same classes moved into layer packages

Terminal
find src/main/java -name "*.java" | sortgrep -rL "^public" src/main/java | sort
Output
$ find src/main/java -name "*.java" | sort
src/main/java/com/shoplite/ShopliteApiApplication.java
src/main/java/com/shoplite/controller/CategoryController.java
src/main/java/com/shoplite/controller/ProductController.java
src/main/java/com/shoplite/dto/CategoryRequest.java
src/main/java/com/shoplite/dto/CategoryResponse.java
src/main/java/com/shoplite/dto/CreateProductRequest.java
src/main/java/com/shoplite/dto/PageResponse.java
src/main/java/com/shoplite/dto/ProductFilter.java
src/main/java/com/shoplite/dto/ProductResponse.java
src/main/java/com/shoplite/dto/UpdateProductRequest.java
src/main/java/com/shoplite/exception/BusinessRuleException.java
src/main/java/com/shoplite/exception/ConflictException.java
src/main/java/com/shoplite/exception/NotFoundException.java
src/main/java/com/shoplite/model/Category.java
src/main/java/com/shoplite/model/Product.java
src/main/java/com/shoplite/repository/CategoryRepository.java
src/main/java/com/shoplite/repository/InMemoryCategoryRepository.java
src/main/java/com/shoplite/repository/InMemoryProductRepository.java
src/main/java/com/shoplite/repository/ProductRepository.java
src/main/java/com/shoplite/service/CategorySampleData.java
src/main/java/com/shoplite/service/CategoryService.java
src/main/java/com/shoplite/service/ProductMapper.java
src/main/java/com/shoplite/service/ProductSampleData.java
src/main/java/com/shoplite/service/ProductService.java

$ grep -rL "^public" src/main/java | sort

What this code does

  • The product feature is spread over five folders: controller, dto, model, repository and service, each also holding category classes.
  • The second command lists files with no public top-level type. It prints nothing: in this layout every class had to be made public so the other layers could reach it.
  • Run both commands from the project folder in Git Bash on Windows or in Terminal on macOS.

Many tutorials start this way, because it matches the three layers. The cost appears as the app grows: each folder fills with classes from every feature, so service holds product, category, customer and order logic side by side.

Every class has to be public, so the controller in controller can reach the service in service. The same openness lets an order class call the product repository directly, and nothing stops it.

Package by feature: product, category, customer, order, common

Package by feature gives each business area (product, category, customer, order) its own package holding its controller, service, repository and DTOs, so everything about one feature lives in one place.

Here is the same app packaged by feature. Everything about products sits in com.shoplite.product.

Example 2 · ShopLite, packaged by feature

Runs in: the shoplite-api Spring Boot project

Terminal
find src/main/java -name "*.java" | sortgrep -rL "^public" src/main/java | sort
Output
$ find src/main/java -name "*.java" | sort
src/main/java/com/shoplite/ShopliteApiApplication.java
src/main/java/com/shoplite/category/Category.java
src/main/java/com/shoplite/category/CategoryController.java
src/main/java/com/shoplite/category/CategoryRepository.java
src/main/java/com/shoplite/category/CategoryRequest.java
src/main/java/com/shoplite/category/CategoryResponse.java
src/main/java/com/shoplite/category/CategorySampleData.java
src/main/java/com/shoplite/category/CategoryService.java
src/main/java/com/shoplite/category/InMemoryCategoryRepository.java
src/main/java/com/shoplite/common/BusinessRuleException.java
src/main/java/com/shoplite/common/ConflictException.java
src/main/java/com/shoplite/common/NotFoundException.java
src/main/java/com/shoplite/common/PageResponse.java
src/main/java/com/shoplite/product/CreateProductRequest.java
src/main/java/com/shoplite/product/InMemoryProductRepository.java
src/main/java/com/shoplite/product/Product.java
src/main/java/com/shoplite/product/ProductController.java
src/main/java/com/shoplite/product/ProductFilter.java
src/main/java/com/shoplite/product/ProductMapper.java
src/main/java/com/shoplite/product/ProductRepository.java
src/main/java/com/shoplite/product/ProductResponse.java
src/main/java/com/shoplite/product/ProductSampleData.java
src/main/java/com/shoplite/product/ProductService.java
src/main/java/com/shoplite/product/UpdateProductRequest.java

$ grep -rL "^public" src/main/java | sort
src/main/java/com/shoplite/category/Category.java
src/main/java/com/shoplite/category/CategoryController.java
src/main/java/com/shoplite/category/CategoryRepository.java
src/main/java/com/shoplite/category/CategorySampleData.java
src/main/java/com/shoplite/category/InMemoryCategoryRepository.java
src/main/java/com/shoplite/product/InMemoryProductRepository.java
src/main/java/com/shoplite/product/Product.java
src/main/java/com/shoplite/product/ProductController.java
src/main/java/com/shoplite/product/ProductMapper.java
src/main/java/com/shoplite/product/ProductRepository.java
src/main/java/com/shoplite/product/ProductSampleData.java

What this code does

  • Every product class is in product, every category class in category, and the shared exceptions and page envelope in common. Customer and order packages arrive later with the same shape.
  • Eleven of the 24 files are package-private: entities, repositories, mappers, controllers and sample-data runners. Only services, DTOs, ProductFilter and the common classes are public.

com.shoplite.product holds the controller, service, repository, its in-memory implementation, the Product entity, the DTOs and ProductMapper; category, customer and order get the same shape. com.shoplite.common holds what every feature shares and no feature owns: the exceptions, PageResponse, and later the global error handler. Common code never depends on a feature.

The layers have not gone away. Inside each feature the controller still calls the service and the service still calls the repository; they are now a few classes in one folder instead of one folder per layer.

Package-private classes to hide a feature's internals

Package-private is the access level of a class or member with no access keyword: only classes in the same package can use it. A feature hides its internals this way.

Here is an order class that imports ProductRepository from the product package, and the error the compiler gives.

The product package has a front door and hidden classes. ProductService and the product DTOs are public. ProductController, ProductRepository, ProductMapper and the Product entity are package-private.

Example 3 · src/main/java/com/shoplite/order/OrderQuoteService.java (reaching into products)

Runs in: a copy of the shoplite-api project with an order package added

OrderQuoteService.javaJava
package com.shoplite.order;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;
import com.shoplite.product.ProductRepository;
// The mistake: the order feature reaches into the product feature's storage@Servicepublic class OrderQuoteService {
    private final ProductRepository products;
    OrderQuoteService(ProductRepository products) {        this.products = products;    }
    public BigDecimal lineTotal(Long productId, int quantity) {        return products.findById(productId).orElseThrow()                .getPrice().multiply(BigDecimal.valueOf(quantity));    }}
Sample output
$ mvn compile
...
[ERROR] COMPILATION ERROR : 
[ERROR] /.../shoplite-api/src/main/java/com/shoplite/order/OrderQuoteService.java:[7,28] com.shoplite.product.ProductRepository is not public in com.shoplite.product; cannot be accessed from outside package
[ERROR] /.../shoplite-api/src/main/java/com/shoplite/order/OrderQuoteService.java:[13,19] com.shoplite.product.ProductRepository is not public in com.shoplite.product; cannot be accessed from outside package
[ERROR] /.../shoplite-api/src/main/java/com/shoplite/order/OrderQuoteService.java:[15,23] com.shoplite.product.ProductRepository is not public in com.shoplite.product; cannot be accessed from outside package
[INFO] BUILD FAILURE

What this code does

  • The order class imports com.shoplite.product.ProductRepository, which is package-private. The compiler refuses the import and both uses of the type.
  • This is the boundary doing its job: in package by layer the same code compiles and quietly skips every product rule.
  • Paths are shortened with ...; yours show your project folder.

In ShopLite's product package the entity, the repository interface and implementation, the mapper, the controller and the sample-data runner are all package-private. Only ProductService and the product DTOs are public: that is the feature's front door.

The compiler now guards the design, because every user of an internal class sits in the same package. Spring creates package-private beans and calls package-private constructors without trouble; public only matters for other Java code.

Fix the error

Use the front door

Read the error, then pick the line that fixes it.

The build fails. Pick the replacement for the highlighted line.

package com.shoplite.order;
import com.shoplite.product.ProductRepository;
class OrderQuoteService {
private final ProductService products;
}

Error

OrderQuoteService.java:3: error: ProductRepository is not public in com.shoplite.product;
  cannot be accessed from outside package
Spring creates package-private beans and calls package-private constructors without trouble. public only matters for other Java code.

How features talk: OrderService uses ProductService, not ProductRepository

A feature's public surface is the small set of classes other features may use: its service and its DTOs. Everything else in the package stays hidden.

Here is OrderQuoteService getting prices through ProductService, and the dependency cycle that appears when a feature calls back.

Example 4 · OrderQuoteService.java, QuoteCheck.java (through the public service)

Runs in: a copy of the shoplite-api project with an order package added

OrderQuoteService.javaJava
package com.shoplite.order;
import java.math.BigDecimal;import java.util.Map;
import org.springframework.stereotype.Service;
import com.shoplite.common.BusinessRuleException;import com.shoplite.product.ProductResponse;import com.shoplite.product.ProductService;
// The order feature asks the product feature's public service, never its repository@Servicepublic class OrderQuoteService {
    private final ProductService products;
    OrderQuoteService(ProductService products) {        this.products = products;    }
    /** Total for a cart of productId -> quantity, using today's prices. */    public BigDecimal quote(Map<Long, Integer> cart) {        BigDecimal total = BigDecimal.ZERO;        for (Map.Entry<Long, Integer> line : cart.entrySet()) {            ProductResponse product = products.get(line.getKey());     // 404 rule lives in ProductService            if (!product.isActive()) {                throw new BusinessRuleException(product.name() + " is no longer sold.");            }            total = total.add(product.price().multiply(BigDecimal.valueOf(line.getValue())));        }        return total;    }}
package com.shoplite.order;
import java.util.LinkedHashMap;import java.util.Map;
import org.springframework.boot.CommandLineRunner;import org.springframework.core.annotation.Order;import org.springframework.stereotype.Component;
import com.shoplite.common.BusinessRuleException;
@Component@Order(3)class QuoteCheck implements CommandLineRunner {
    private final OrderQuoteService quotes;
    QuoteCheck(OrderQuoteService quotes) {        this.quotes = quotes;    }
    @Override    public void run(String... args) {        Map<Long, Integer> cart = new LinkedHashMap<>();        cart.put(9L, 2);        cart.put(6L, 1);        System.out.println("Quote for cart " + cart + ": Rs " + quotes.quote(cart));
        try {            quotes.quote(Map.of(15L, 1));   // USB-C Cable 1m, inactive        } catch (BusinessRuleException e) {            System.out.println("Refused: " + e.getMessage());        }    }}
Output
Quote for cart {9=2, 6=1}: Rs 2297.00
Refused: USB-C Cable 1m is no longer sold.

What this code does

  • OrderQuoteService depends on ProductService and works only with ProductResponse records: price, name and isActive. A missing id would raise the product feature's own NotFoundException.
  • Two Clean Code at 499.00 plus one Airdopes at 1299.00 give 2297.00. The inactive USB-C cable is refused with the order feature's own rule.
  • QuoteCheck is a temporary runner with @Order(3), so it runs after the category and product sample data are loaded. The real order feature comes in the last module of this section.

Example 5 · CategoryService.java calling ProductService back: a cycle

Runs in: a copy of the shoplite-api project

Java
// src/main/java/com/shoplite/category/CategoryService.java (changed parts)    private final CategoryRepository repository;    private final ProductService productService;   // category -> product
    CategoryService(CategoryRepository repository, ProductService productService) {        this.repository = repository;        this.productService = productService;    }
    public void delete(Long id) {        load(id);        if (productService.existsInCategory(id)) {            throw new ConflictException("Category " + id + " has products and cannot be deleted.");        }        if (repository.existsByParentId(id)) {            throw new ConflictException("Category " + id + " has sub-categories and cannot be deleted.");        }        repository.deleteById(id);    }
// src/main/java/com/shoplite/product/ProductService.java (added method)    public boolean existsInCategory(Long categoryId) {        ProductFilter inCategory = new ProductFilter(null, categoryId, null, null, false, true);        return repository.count(inCategory) > 0;    }
Sample output

***************************
APPLICATION FAILED TO START
***************************

Description:

The dependencies of some of the beans in the application context form a cycle:

   categoryController defined in file [...\shoplite-api\target\classes\com\shoplite\category\CategoryController.class]
┌─────┐
|  categoryService defined in file [...\shoplite-api\target\classes\com\shoplite\category\CategoryService.class]
↑     ↓
|  productService defined in file [...\shoplite-api\target\classes\com\shoplite\product\ProductService.class]
└─────┘


Action:

Relying upon circular references is discouraged and they are prohibited by default. Update your application to remove the dependency cycle between beans. As a last resort, it may be possible to break the cycle automatically by setting spring.main.allow-circular-references to true.

What this code does

  • The goal is fair (the contract says a category with products cannot be deleted), but ProductService already needs CategoryService, so neither bean can be created first.
  • The box in the report draws the cycle: categoryService needs productService, which needs categoryService. Do not switch on allow-circular-references; remove one arrow.
  • ShopLite keeps product → category. The "has products" check comes with MySQL: the category repository runs a COUNT on the products table, and the foreign key from products to categories refuses the delete anyway.

Features talk through their public services, never through each other's repositories. An order feature that needs a price asks ProductService.get(id) and receives a ProductResponse; it never sees the Product entity. The product rules always run, and the product feature can change its storage without breaking orders.

Keep these calls one-way. When two features seem to need each other, let the database answer (a query or a foreign key) or move the shared check into one side. Which calls are allowed:

  • product → category: allowed (names and the "category must exist" rule).
  • order → product, order → customer: allowed (prices, stock, addresses).
  • category → product as well as product → category: a cycle; Spring stops.
  • any feature → common: allowed. common → any feature: never.

Why ShopLite uses package by feature as it grows

ShopLite grows section by section: validation, error handling, MySQL repositories, JPA, security. With packages by feature, each of those changes lands inside the feature it touches, and a new feature is one new folder that copies the shape of an existing one.

Reviewers and interviewers can open com.shoplite.order and see the whole order story in one place. Deleting or splitting a feature later (say, moving orders into their own service) is a matter of moving one package.

Package by layer is still fine for a tiny app or a short demo. Choose package by feature when the app has several business areas and is meant to grow, which is exactly ShopLite's plan.

  • One change, one folder: everything about a feature sits together.
  • Small public surface: services and DTOs public, everything else hidden.
  • Feature-to-feature calls go through services and point one way.
  • Shared code lives in common, which depends on no feature.

Next step

Check your understanding

12 quick questions