Note that there are some explanatory texts on larger screens.

plurals
  1. POStrategy pattern with spring beans
    primarykey
    data
    text
    <p>Say I'm using spring, I have the following strategies...</p> <p>Interface</p> <pre><code>public interface MealStrategy { cook(Meat meat); } </code></pre> <p>First strategy</p> <pre><code>@Component public class BurgerStrategy implements MealStrategy { @Autowired CookerDao cookeryDao; @Override public void cook(Meat meat) { cookeryDao.getBurger(meat); } } </code></pre> <p>Next strategy...</p> <pre><code>@Component public class SausageStrategy implements MealStrategy { @Autowired CookerDao cookeryDao; @Override public cook(Meat meat) { return cookeryDao.getSausage(meat); } } </code></pre> <p>Context...</p> <pre><code>@Component @Scope("prototype") public class MealContext { private MealStrategy mealStrategy; public void setMealStrategy(MealStrategy strategy) { this.strategy = strategy; } public void cookMeal(Meat meat) { mealStrategy.cook; } } </code></pre> <p>Now say this context was being accessed through an mvc controller, like...</p> <pre><code>@Autowired private MealContext mealContext; @RequestMapping(method = RequestMethod.POST) public @ResponseBody Something makeMeal(Meat meat) { mealContext.setMealStrategy(new BurgerStrategy()) mealContext.cookMeal(meat); } </code></pre> <p>Should the context be a component? When I do I get an error saying loadOnStartup an there's a nonUniqueBean that the strategy could be, as you'd expect. Do all of the beans need to be components like above or are my annotations incorrect?</p> <p>My biggest query really is can you use a context like that in a Spring MVC app? The problem I have with using @Scope(prototype) too is it means the cookeryDao calls in the strategies return a null pointer as the Dao's don't get injected.</p> <p>How would I implement the above pattern using spring and also be thread safe? Is what I'm trying even possible?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload