解决Springboot 自动注入报空指针问题

2019-05-07  本文已影响0人  进击的三文鱼

最近做发送邮件的功能,因为邮件的种类有多种,所以使用了多态,工厂模式。建立了一个抽象接口,以及实现类,根据传入不同的邮件类型进行调用不同类中的方法。
但是遇到了问题,在调用实现类时,发现实现类中自动注入的service不生效,全部为空。
代码如下

     IShMessageEmailService shMessageEmailService;
        if (messageType.equals("etaMessage")) {
            shMessageEmailService = new ShMessageEmailEtaService();
            text = shMessageEmailService.getMessageText(dynamicEntity, sailingSchedule, messageType);
        } else if (messageType.equals("etdMessage")) {
            shMessageEmailService = new ShMessageEmailEtdService();
            text = shMessageEmailService.getMessageText(dynamicEntity, sailingSchedule, messageType);
        }
@Service
public class ShMessageEmailEtaService extends BusinessService implements IShMessageEmailService {

    @Autowired
    private ShManifestCargoService shManifestCargoService;
    @Autowired
    private ShipPortService shipPortService;
  @Override
    public String getMessageText(ShDynamic dynamic, SailingSchedule sailingSchedule, String messageType) {
        ShManifestCargo shManifestCargo = shManifestCargoService.findImpCargoAndBlNo(sailingSchedule.getId());
        String loadPortCode = "";

检查后发现,又来是spring的service管理问题,如果用了spring管理bean 就不能自己new出来,然后修正了代码

@Autowired
    private ShMessageEmailEtaService shMessageEmailEtaService;
    @Autowired
    private ShMessageEmailEtdService shMessageEmailEtdService;
 IShMessageEmailService shMessageEmailService;
        if (messageType.equals("etaMessage")) {
            shMessageEmailService = shMessageEmailEtaService;
            text = shMessageEmailService.getMessageText(dynamicEntity, sailingSchedule, messageType);
        } else if (messageType.equals("etdMessage")) {
            shMessageEmailService = shMessageEmailEtdService;
            text = shMessageEmailService.getMessageText(dynamicEntity, sailingSchedule, messageType);
        }

这样就ok了。

上一篇下一篇

猜你喜欢

热点阅读