Decorator Pattern in Spring
public class BasicProductService implements ProductService {
private final ProductRepository productRepo;
public BasicProductService(ProductRepository productRepo) {
this.productRepo = productRepo;
}
@Override
public Product createProduct(String productName) {
// simplified implementation for brevity
Product product = new Product(productName);
productRepo.save(product);
return product;
}
}public class FullTextSearchIndexedDecorator implements ProductService {
private final ProductService wrappedProductService;
private final FullTextSearchIndexService fullTextSearchIndexService;
public FullTextSearchIndexedDecorator(
ProductService wrappedProductService,
FullTextSearchIndexService fullTextSearchIndexService) {
this.wrappedProductService = wrappedProductService;
this.fullTextSearchIndexService = fullTextSearchIndexService;
}
@Override
public Product createProduct(String productName) {
Product product = wrappedProductService.createProduct(productName);
fullTextSearchIndexService.index(product);
return product;
}
}Multiple implementations of an interface in a single Spring context
A single implementation of an interface in Spring context
only the basic implementation is created as a bean, other components can use base implementation and decorate it if needed
only the decorated implementation is created as a bean, all other components which are using auto-wiring will get the decorated implementation
Last updated
Was this helpful?