Как внедрить услугу внутри поставщика.Репозиторий пуст - PullRequest
0 голосов
/ 08 июля 2019

Я создал фабричный шаблон, используя поставщика.Это нормально, и все работало нормально.Путь к правильному сервису в порядке, но внутри сервиса, который будет рассчитывать, репозитории нулевые.Кажется, он не подключается автоматически.

Я пытался автоматически связать и аннотировать классы с помощью @Service и @Component, но все еще не работает.

@Service
public class Service {

    public responseDTO calculate(Contract contract, Request request) {

        Supplier<TypeFactory> type = TypeFactory::new;

        //HOW TO AUTOWIRE THIS?
        return type.get().getCalculationMethod(contract.getId()).calculate(request);

    }

}


@Service
public class TypeFactory {

    final static Map<Integer, Supplier<Calculator>> calculationTypeMap = new HashMap<>();

    static {
        calculationTypeMap.put(1, ContractOneType::new);
        calculationTypeMap.put(2, ContractTwoType::new);
    }

    public Calculator getCalculationMethod(Integer type) {
        Supplier<Calculator> method = calculationTypeMap.get(type);
        if (method != null) {
            return method.get();
        }
        throw new IllegalStateException("Type not found");
    }

}
@Service
public interface Calculator {

    ResponseDTO calculate(Request Request);

}
@Service
public class ContractOneType implements Calculator {

    @Autowired
    private ContractRepository contractRepository;

    public ResponseDTO calculate(Request request) {

        ResponseDTO responseDTO = new ResponseDTO();

        Contract contract = contractRepository.findById(request.getId()).orElseThrow(() -> new NotFoundException("id not found"));

        //some calculations here with the contract

        return responseDTO;

    }

}

Контрактный репозиторий имеет значение NULL, не подключается автоматически.Должно быть.

Сообщения об ошибках из моего кода:

2019-07-08 10: 19: 33.078 ОШИБКА [-, 21fa294c89e1e207,21fa294c89e1e207, false] 19477 --- [nio-8080-exec-1] cldtshGeneralExceptionHandler: msg = "Exception", stacktrace = "java.lang.NullPointerException

1 Ответ

0 голосов
/ 08 июля 2019

Я нашел решение, меняющее моего поставщика, которое создает новые экземпляры, я просто создаю экземпляры для своих реализаций и устанавливаю для них @Autowired.

И именно поэтому мой репозиторий не является @Autowired.

Вот мой код:

@Service
public class TypeFactory {

    final static Map<Integer, Supplier<Calculator>> calculationTypeMap = new HashMap<>();

    @Autowired
    ContractOneType contractOneType;

    @Autowired
    ContractTwoType contractTwoType;

    static {
        calculationTypeMap.put(1, contractOneType);
        calculationTypeMap.put(2, contractTwoType);
    }

    public Calculator getCalculationMethod(Integer type) {
        Supplier<Calculator> method = calculationTypeMap.get(type);
        if (method != null) {
            return method.get();
        }
        throw new IllegalStateException("Type not found");
    }

}
@Component
public class ContractOneType implements Calculator {

    @Autowired
    private ContractRepository contractRepository;

    public ResponseDTO calculate(Request request) {

        ResponseDTO responseDTO = new ResponseDTO();

        Contract contract = contractRepository.findById(request.getId()).orElseThrow(() -> new NotFoundException("id not found"));

        //some calculations here with the contract

        return responseDTO;

    }

}
public interface Calculator {
    ResponseDTO calculate(Request Request);

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...