Skip to content
Advertisement

How to implement Decorator pattern in Spring Boot

I know how to implement and use a decorator pattern without Spring.

Because in this pattern you yourself control the process of creating components and you can perform dynamic behavior adding.

Below is an example of implementation without using Spring:

JavaScript

I am interested in how to implement the same example but with the help of spring beans.

Because I don’t quite understand how to maintain flexibility in the ability to simply wrap with any number of decorators.

Because as I understand it – it will be implemented fixed in some separate component and I will have to create dozens of various separate components with the combinations of decorators I need.

Advertisement

Answer

I haven’t really understood what is your actual problem here, but I’ll try anyway.
Say you have these classes

JavaScript

Each of these require an instance of a Printer, which, let’s say is provided as a Spring @Component. To use each decorator as Spring Bean you need to register it.

JavaScript

You can then use the @Qualifier annotation to get the right one @Autowired

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement