工厂方法 return Spring 服务

Factory Method return Spring service

我想要一个工厂class,return 一个我可以用来做一些验证的服务。我实现了这个 class

public class EventUpdateValidatorFactory {

    public EventUpdateValidatorStrategy getValidator(EEventStatus eventStatus) {

        if (SECOND_APPROVAL.equals(eventStatus)) {
            return new EventSecondApprovalValidator();
        } else if (APPROVED.equals(eventStatus)) {
            return new EventApprovedValidator();
        } else if (ACCOUNTING_HQ.equals(eventStatus)) {
            return new EventAccountingHqValidator();
        }

        throw new IllegalArgumentException("Unknown status");
    }
}

接口EventUpdateValidatorStrategy是这个

public interface EventUpdateValidatorStrategy {

    default <T extends EventUpdateValidatorStrategy> void validate(User user, EventMasterData masterData, Event event, List<EventExternalSystemExpenseSave> expenses,
            List<EventExternalSystemSpeakerSave> speakers, long eventId) {

        this.validateMasterData(masterData, event);
        this.validateSpeakers(speakers, eventId);
        this.validateExpenses(expenses, eventId);
        this.doUpdate(user, masterData, expenses, speakers, eventId);

    }

    void validateMasterData(EventMasterData masterData, Event event);
    void validateExpenses(List<EventExternalSystemExpenseSave> expenses, long eventId);
    void validateSpeakers(List<EventExternalSystemSpeakerSave> speakers, long eventId);
    void doUpdate(User user, EventMasterData masterData, List<EventExternalSystemExpenseSave> expenses, List<EventExternalSystemSpeakerSave> speakers, long eventId);

}

EventSecondApprovalValidator是这个

@Service
@Transactional
public class EventSecondApprovalValidator implements EventUpdateValidatorStrategy {

    @Autowired
    private EventService eventService;

    @Autowired
    private ContextDateService contextDateService;

    @Autowired
    private EventExpenseService eventExpenseService;

    @Autowired
    private EventExternalSystemDAO eventExternalSystemDAO;

    @Override
    public void validateMasterData(LocalEventMasterData masterData, Event event) {
        // some logic
    }

    @Override
    public void validateExpenses(List<EventExternalSystemExpenseSave> expenses, long eventId) {
        // some logic
    }

    @Override
    public void validateSpeakers(List<EventExternalSystemSpeakerSave> speakers, long eventId) {
        // some logic
    }

    @Override
    public void doUpdate(User user, EventMasterData masterData, List<EventExternalSystemExpenseSave> expenses, List<EventExternalSystemSpeakerSave> speakers, long eventId) {
        ofNullable(expenses).ifPresent(expensesToSave -> expensesToSave.forEach(expense -> this.eventExternalSystemDAO.updateExpense(user, expense)));
        this.eventExternalSystemDAO.updateEvent(user, masterData, eventId);
    }

}

其他 EventApprovedValidatorEventAccountingHqValidator 实现类似。

我从主代码调用

final EventUpdateValidatorStrategy validator = EventUpdateValidatorFactory.getValidator(event.getStatus());
        validator.validate(user, eventSave.getMasterData(), event, eventSave.getExpenses(), eventSave.getSpeakers(), eventID);

结果是,当我进入 EventSecondApprovalValidator 时,所有自动装配的服务都是空的,显然,我第一次使用其中一项服务时收到 NPE .

我如何根据 EEventStatus 正确使用工厂 return 我需要的服务?

手动创建对象不会让 Spring 执行自动装配。也可以考虑通过 Spring 管理您的服务。

 @Component
public class MyServiceAdapter implements MyService {

    @Autowired
    private MyServiceOne myServiceOne;

    @Autowired
    private MyServiceTwo myServiceTwo;

    @Autowired
    private MyServiceThree myServiceThree;

    @Autowired
    private MyServiceDefault myServiceDefault;

    public boolean checkStatus(String service) {
        service = service.toLowerCase();

        if (service.equals("one")) {
            return myServiceOne.checkStatus();
        } else if (service.equals("two")) {
            return myServiceTwo.checkStatus();
        } else if (service.equals("three")) {
            return myServiceThree.checkStatus();
        } else {
            return myServiceDefault.checkStatus();
        }
    }
}

EventUpdateValidatorFactory.getValidator(EEventStatus) 方法中,您需要 return 来自上下文的 EventSecondApprovalValidator bean,而不是使用 new 关键字创建新实例。

class EventSecondApprovalValidator@Service 注释的(假设只有一个这种类型),这种类型的实例将被添加到 ApplicationContext 通过Spring 注入了所有依赖项。所以,只需从上下文中获取它并使用它。

一个快速的方法如下:

public EventUpdateValidatorStrategy getValidator(ApplicationContext context, 
        EEventStatus eventStatus) {

    if (SECOND_APPROVAL.equals(eventStatus)) {
        return context.getBean(EventSecondApprovalValidator.class);
    } else if (APPROVED.equals(eventStatus)) {
        return context.getBean(EventApprovedValidator.class);
    } else if (ACCOUNTING_HQ.equals(eventStatus)) {
        return context.getBean(EventAccountingHqValidator.class);
    }

    throw new IllegalArgumentException("Unknown status");
}

您还可以 @Autowire EventUpdateValidatorFactory 和 return @Autowired 实例中的所有验证器。这将使 getValidator 方法的签名保持不变,但您必须使 EventUpdateValidatorFactory 成为 @Component-esque class.

@Component
public class EventUpdateValidatorFactory {

    @Autowired
    EventSecondApprovalValidator a;

    @Autowired
    EventApprovedValidator b;

    @Autowired
    EventAccountingHqValidator c;

    public EventUpdateValidatorStrategy getValidator(EEventStatus eventStatus) {

        if (SECOND_APPROVAL.equals(eventStatus)) {
            return a;
        } else if (APPROVED.equals(eventStatus)) {
            return b;
        } else if (ACCOUNTING_HQ.equals(eventStatus)) {
            return c;
        }

        throw new IllegalArgumentException("Unknown status");
    }