E
E
Evgeniy Rybalko2020-07-05 17:22:07
Java
Evgeniy Rybalko, 2020-07-05 17:22:07

How to implement a factory method in Spring?

Good afternoon
Please tell me how to implement a factory method in Spring boot.

The example below shows a method that creates one of the implementations of the State interface.

public State getState(Long chatId) throws NoSuchMethodException,
            IllegalAccessException, InvocationTargetException, InstantiationException {
        ChatState chatState = getChatState(chatId);
        DescriptorDto dto = getDescriptorByChat(chatState);
        State state = this.getStateClass(dto).getDeclaredConstructor(String.class, String.class,
                String.class, String.class, List.class)
                .newInstance(dto.getState(), dto.getNextState(),
                        dto.getText(), dto.getErrorState(), null);
        return state;
    }


The problem is that some implementations of this interface require access to other components of the spring.
Since there is a simple constructor here, I do not have the opportunity to refer to them (or in the constructor itself to transfer some default service to all classes)

Tell me. what to do?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question