Strategy within Spring boot

ringadingding :

Hi I have a strategy pattern in a spring boot application. All my strategies have autowired constructors. I am new to spring boot. I do not have a simplest of idea how am I going to write my factory for strategy classes as autowired constructors have injected dependencies. I appreciate any help I get with this.

NOTE: I am leaving out out Intefaces and base classes to not to clutter sample.

public class StrategyA implement Strategy {
private DependencyA depA;
private DependencyB depB;
   @Autowired
   public StragegyA(DependencyA depA, DependencyB depB) {
       this.depA = depA;
       this.depB = depB;
   }
}

public class StrategyB implements Strategy {
private DependencyA depA;
private DependencyB depB;
   @Autowired
   public StragegyB(DependencyA depA, DependencyB depB) {
       this.depA = depA;
       this.depB = depB;
   }
}

public class StrategyFactory {
    public Strategy getStrategy(String strategyName) {
      if (name.equals("StrategyA")) {
         <b>return StrategyA; //My problem is here
      } else {
         return StrategyB; // And Here
      }
    }
}
JEY :

All the previous answers are using a pretty straight forward usage of spring DI. However it's also possible to use ServiceLocatorFactoryBean in order to create a factory without having to specify any bean in the factory. First define a interface for your factory:

public interface MyFactory {
    Strategy get(String type);
}

// Could be an abstract class
public interface Strategy {
    void doStuff();
}

Then in your application:

@Configuration
public class AppConfiguration {
    @Autowired
    private BeanFactory beanFactory;

    public ServiceLocatorFactoryBean myFactoryLocator() {
        final ServiceLocatorFactoryBean locator = new ServiceLocatorFactoryBean();
        locator.setServiceLocatorInterface(MyFactory.class);
        locator.setBeanFactory(beanFactory);
        return locator;
    }

    @Bean
    public MyFactory myFactory() {
        final ServiceLocatorFactoryBean locator = myFactoryLocator();
        locator.afterPropertiesSet();
        return (MyFactory) locator.getObject();
    }
}

Now you can define bean (using annotation @Service, @Component or @Bean) that implements/extends and they are automatically registered into the MyFactory bean and can be created with:

myFactory.get("beanName");

The best part is you can register the Strategy bean as lazy and with different scopes.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458780&siteId=1