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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Trending

  • Designing Frontend Applications for Failure, Not Just Success
  • Kafka With Spring Boot: Introduction
  • Beyond @Transactional: Solving the Dual-Write Problem in Distributed Microservices
  • Claude Code Superpowers: The 5-Tool Stack That Ends Limits and Context Amnesia

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Boot: Strategy Design Pattern - Convenience and Limitations

Spring Boot: Strategy Design Pattern - Convenience and Limitations

By 
Karl Heinz Marbaise
·
Oct. 05, 20 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.0K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

You might have already used the strategy pattern in relationship with Spring Boot where it is very convenient to use. You simply define an interface for example (I use the prefixing I only in these examples for clarity):

Java
xxxxxxxxxx
1
 
1
public interface IOneStrategy {
2
  void executeTheThing();
3
}


Define some implementations like this:

Java
xxxxxxxxxx
1
 
1
@Service("FIRST")
2
public class OneStrategyFirst implements IOneStrategy {
3
4
  @Override
5
  public void executeTheThing() {
6
    System.out.println("OneStrategyFirst.executeTheThing");
7
  }
8
}


Now, you can simply implement a service, which will execute the appropriate strategy based on the given name which looks similar like this:

Java
xxxxxxxxxx
1
16
 
1
@Service
2
public class ExecuteStrategyOne {
3
  private Map<String, IOneStrategy> strategies;
4
5
  public ExecuteStrategyOne(Map<String, IOneStrategy> strategies) {
6
    this.strategies = strategies;
7
  }
8
9
  public void executeStrategyOne(String name) {
10
    if (!strategies.containsKey(name)) {
11
      throw new IllegalArgumentException("The strategy " + name + " does not exist.");
12
    }
13
    strategies.get(name).executeTheThing();
14
  }
15
   
16
}


In the real world, you make several implementations of the strategy interface like OneStrategyFirst, OneStrategySecond, and OneStrategyThird. Sometimes, the usage is to use the parameter of executeStrategyOne, which is provided by a REST API or some other domain specific code which needs different implementations.

The convenience here is that Spring Boot (Spring Framework to be more accurate) handles the injection of the different implementation into the strategies Map within ExecuteStrategyOne via the constructor. This results in a Map where the key is the value which is given by @Service("FIRST") and the value of the map contains an instantiates class of every implementation of the interface IOneStrategy which can be found.

Really convenient. 

In real life, it happens that you need to have a different strategy which use the same keys as FIRST, SECOND, and THIRD in the examples? Let us define the following:

Java
xxxxxxxxxx
1
 
1
@Service("FIRST")
2
public class TwoStrategyFirst implements ITwoStrategy {
3
4
  @Override
5
  public void executeTheThing() {
6
    System.out.println("TwoStrategyFirst.executeTheThing");
7
  }
8
}


If you try to start that Spring Boot application you will see an exception like this:

Plain Text
xxxxxxxxxx
1
 
1
Caused by: org.springframework.context.annotation.ConflictingBeanDefinitionException: 
2
Annotation-specified bean name 'FIRST' for bean class [com.soebes.examples.strategies.functions.two.TwoStrategyFirst] 
3
conflicts with existing, non-compatible bean definition of same name and class 
4
[com.soebes.examples.strategies.functions.one.OneStrategyFirst]
5
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.checkCandidate(ClassPathBeanDefinitionScanner.java:349) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
6
    at org.springframework.context.annotation.ClassPathBeanDefinitionScanner.doScan(ClassPathBeanDefinitionScanner.java:287) ~[spring-context-5.2.9.RELEASE.jar:5.2.9.RELEASE]
7


So what can we do to solve the problem without losing much of the convenience which Spring Boot provides us here?

First we have to define in each of the strategy implementation class the annotations like this:

Java
xxxxxxxxxx
1
 
1
@Service
2
@Qualifier("FIRST")
3
public class TwoStrategyFirst implements ITwoStrategy {
4
5
  @Override
6
  public void executeTheThing() {
7
    System.out.println("TwoStrategyFirst.executeTheThing");
8
  }
9
}


By using the key in a different annotation we prevent the duplication of the bean names in contradiction to use @Service("FIRST") instead. The usage of @Qualifier("FIRST") gives us a criteria to handle that different.

Now we have to change the ExecuteStrategyOne class like the following:

Java
xxxxxxxxxx
1
12
 
1
public class ExecuteStrategyOne {
2
3
  private Map<String, IOneStrategy> strategies;
4
5
  public ExecuteStrategyOne(List<IOneStrategy> strategies) {
6
    this.strategies = strategies.stream()
7
        .collect(
8
            toMap(k -> k.getClass().getDeclaredAnnotation(Qualifier.class).value(), 
9
                  Function.identity()));
10
  }
11
  ...
12
}


I would like to emphasis the usage of the constructor parameter List<IOneStrategy> strategies instead of the previously used Map<String, IOneStrategy> strategies which is a convenience to get a list of all implementations off the given interface into that list by Spring Boot. Now we need to translate that into a map with the key we have defined by using @Qualifier annotation. The whole thing can be solved by a stream like this:

Java
x
 
1
this.strategies = strategies
2
  .stream()
3
  .collect(
4
    Collectors.toMap(k -> k.getClass().getDeclaredAnnotation(Qualifier.class).value(), 
5
                     Function.identity()));


We go through the implementations and extract the annotation @Qualifier and read out the value() which is the key we want to have. We collect the result by using the Collectors.toMap into a Map and assign the result to the instance variable private Map<String, IOneStrategy> strategies. Depending on your need it is of course possible to define the instance variable as final and you can create an unmodifiable map by using the appropriate Collectors.toUnmodifiableMap instead of the toMap(..) if needed.

So with a few changes in the code we can easily solve the problem of having different strategies which using the same keys in our code.

The given code is available as a full working example on GitHub. 

Spring Framework Spring Boot Design

Opinions expressed by DZone contributors are their own.

Related

  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4
  • How Spring Boot Starters Integrate With Your Project
  • A Practical Guide to Creating a Spring Modulith Project
  • Structured Logging in Spring Boot 3.4 for Improved Logs

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook