Springboot:策略模式+工厂模式注入

今天把项目中以前的代码优化了下,使用策略+工厂模式。中途也出现了一些问题,最够还是查资料解决了。链接放最后,有兴趣可以看看原文。

最大的问题就是工厂注入的问题:

这是策略实现类里面的内容,需要用mapper用查询数据库

//策略总接口
public interface NewsStrategy{



    PageInfo<News>   query(NewsRequestDTO dto, PageUtil pageUtil);

     void getResult(News news, User user,Map<String, Object> map) throws JsonProcessingException;
}
//实现类
@Component
@Data
public class NewsOrganStrategy implements NewsStrategy{

    @Autowired
    private OrganMapper organMapper;
    @Autowired
    private NewsMapper newsMapper;
    @Override
    public PageInfo<News>  query(NewsRequestDTO dto, PageUtil pageUtil) {



        PageInfo<News> pageInfo = PageHelper.startPage(pageUtil.getCurrentPage(), pageUtil.getPageSize())
                .doSelectPageInfo(() -> {
                    newsMapper.getNewsListByParams(dto.query, null, null, dto.beginTime, dto.endTime, dto.newsTitle, dto.type, dto.unbindedRoomUserCanSeeFlag==1?true:false, dto.examine == -1 ? null : dto.examine);
                });
        return pageInfo;
    }

    @Override
    public void getResult(News news, User user, Map<String,Object> map) throws JsonProcessingException {
    业务逻辑  。。。
    }
}

这是工厂,使用的时候根据id获取不同的实现类。

public class NewsStrategyFactory{

    public static NewsStrategy getNewsStrategy(Integer rangTypeId) {

        switch (rangTypeId) {
            case 0:
                return new NewsNationwideStrategy();
            case 1:
                return new NewsOrganStrategy();
            case 2:
                return new NewsCommStrategy();
            case 3:
                return new NewsProjectStrategy();
            default:
                throw new ServiceException("不支持的层级类型");
        }


    }


}

获取具体的实现类时候,调用静态方法。

NewsStrategy newsStrategy = NewsStrategyFactory.getNewsStrategy(dto.getRangeTypeId());

在调试过程,一直在mapper调用查询方法时,报空指针。这块困惑了很久,最后才发现,我虽然在策略实现类上加了@Componen注解,但在使用工厂类得到对象实际上是new 出来的策略对象new来的对象本身使用的不是spring容器中bean,所以其中的mapper属性虽然有@Autowired注解,但属性实际是空的。

在网上查了相关问题后,最终解决了。

贴上答案:

spring支持多个实现类注入到Map和List。

 当一个接口有多个实现类的时候,key为实现类名(首字母小写),value为实现类对象

我们需要把工厂类也注入到spring容器中

@Component
public class NewsStrategyFactory{

    @Autowired
    private Map<String,NewsStrategy> newsStrategyMap;

//    @Autowired
//    private List<NewsStrategy> newsStrategyList;



    public  NewsStrategy getNewsStrategy(Integer rangTypeId) {

        switch (rangTypeId) {
            case 0:
                return newsStrategyMap.get("newsNationwideStrategy");
            case 1:
                return newsStrategyMap.get("newsOrganStrategy");
            case 2:
                return newsStrategyMap.get("newsProjectStrategy");
            case 3:
                return newsStrategyMap.get("newsCommStrategy");
            default:
                throw new ServiceException("不支持的层级类型");
        }


    }


}

使用的时候,在使用的类中也注入工厂就好了,用注入的工厂获取策略对象就行了

    @Autowired
    private NewsStrategyFactory newsStrategyFactory;


   

参考:基于SpringBoot的策略模式多实现类注入(Map注入)-pudn.com

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中使用策略模式和依赖注入可以通过以下步骤实现: 1. 创建策略接口和多个实现类,例如: ```java public interface PaymentStrategy { void pay(double amount); } @Component public class CreditCardPaymentStrategy implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("Paid " + amount + " using credit card."); } } @Component public class PayPalPaymentStrategy implements PaymentStrategy { @Override public void pay(double amount) { System.out.println("Paid " + amount + " using PayPal."); } } ``` 2. 创建一个策略工厂类,用于根据不同的条件返回不同的策略实现类,例如: ```java @Component public class PaymentStrategyFactory { private final CreditCardPaymentStrategy creditCardPaymentStrategy; private final PayPalPaymentStrategy payPalPaymentStrategy; @Autowired public PaymentStrategyFactory(CreditCardPaymentStrategy creditCardPaymentStrategy, PayPalPaymentStrategy payPalPaymentStrategy) { this.creditCardPaymentStrategy = creditCardPaymentStrategy; this.payPalPaymentStrategy = payPalPaymentStrategy; } public PaymentStrategy getPaymentStrategy(String paymentMethod) { if ("creditCard".equalsIgnoreCase(paymentMethod)) { return creditCardPaymentStrategy; } else if ("payPal".equalsIgnoreCase(paymentMethod)) { return payPalPaymentStrategy; } else { throw new IllegalArgumentException("Invalid payment method: " + paymentMethod); } } } ``` 3. 在需要使用策略的地方,注入策略工厂,并根据条件获取对应的策略实现类,例如: ```java @RestController public class PaymentController { private final PaymentStrategyFactory paymentStrategyFactory; @Autowired public PaymentController(PaymentStrategyFactory paymentStrategyFactory) { this.paymentStrategyFactory = paymentStrategyFactory; } @PostMapping("/pay") public void pay(@RequestParam String paymentMethod, @RequestParam double amount) { PaymentStrategy paymentStrategy = paymentStrategyFactory.getPaymentStrategy(paymentMethod); paymentStrategy.pay(amount); } } ``` 在上述代码中,我们使用了Spring Boot的依赖注入功能,将策略实现类注入到策略工厂中,并将策略工厂注入到控制器中。在控制器中,我们根据请求参数获取对应的策略实现类,并调用其方法完成支付操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值