I'm implementing the strategy pattern using spring and to Load the correct strategy implementation, follow this example:
public class ShippingServiceImpl implements ShippingService {
// Map of strategies
private Map<ShippingType,ShippingCostStrategy> shippingCostStrategies;
@Required
public void setShippingCostStrategies(Map<ShippingType,ShippingCostStrategy> strategies) {
this.shippingCostStrategies = strategies;
}
@Override
public BigDecimal calculateShippingCost(ShoppingCart cart) {
return shippingCostStrategies.get(cart.getShippingType()).shippingCost(cart);
}
// ...other business logic...
}
How is the best way to Load this strategy Map? I want a specific method that loads the map and pass to setShippingCostStrategies ? Can i do it using spring Annotations? because in this example, the author do it using configuration:
<bean id="shippingService" class="it.nicus.springstrategy.ShippingServiceImpl">
<property name="shippingCostStrategies">
<map>
<entry>
<key><util:constant static- field="it.nicus.springstrategy.ShippingType.NORMAL"/></key>
<bean class="it.nicus.springstrategy.PerItemCostStrategyImpl">
<property name="baseCost" value="5.00"/>
<property name="costPerItem" value="2.00"/>
</bean>
</entry>
<entry>
<key><util:constant static- field="it.nicus.springstrategy.ShippingType.PRIME"/></key>
<bean class="it.nicus.springstrategy.FixedCostStrategyImpl">
<property name="fixedCost" value="3.00" />
</bean>
</entry>
</map>
</property>
</bean>
You can register the map
as bean using <util:map>
tag, and then use @Resource
annotation to autowire that map.
<util:map id="strategyMap">
<entry>
<key>
<util:constant static-field="it.nicus.springstrategy.ShippingType.NORMAL" />
</key>
<bean class="it.nicus.springstrategy.PerItemCostStrategyImpl">
<property name="baseCost" value="5.00" />
<property name="costPerItem" value="2.00" />
</bean>
</entry>
<entry>
<key>
<util:constant static-field="it.nicus.springstrategy.ShippingType.PRIME" />
</key>
<bean class="it.nicus.springstrategy.FixedCostStrategyImpl">
<property name="fixedCost" value="3.00" />
</bean>
</entry>
</util:map>
And then, in ShippingServiceImpl
class, inject it like this:
public class ShippingServiceImpl implements ShippingService {
// Map of strategies
@Resource(name="strategyMap")
private Map<ShippingType,ShippingCostStrategy> shippingCostStrategies;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.