samedi 25 décembre 2021

Dependency Injection with Strategy and factory pattern in spring boot

I have recently implemented Strategy + Factory Method pattern in my application, but in my implementation class i am not able to initialise object. Getting Null pointer exception : cannot invoke method

@Component
class someClass {

private final StrategyFactory strategyFactory

    someClass(StrategyFactory strategyFactory) {
        strategyFactory = strategyFactory
    }

Request strategy = strategyFactory.getBanks(getBankName)
                        .orElseThrow({ -> new IllegalArgumentException("No Bank found with the name " + getBankName) })

            strategy.fetch(getBankName)
}

Actual factory class , can we use @autowired instance here instead using new keyword

@Component
class StrategyFactory {

    private Map<String, BankNameRequest> name = new HashMap<>()

    StrategyFactory() {
        name.put("sbi", new SBIService())
        name.put("hdfc", new HDFCService())
        name.put("union", new UnionService())
    }

    Optional< BankNameRequest > getBanks(String bname) {
        return Optional.ofNullable(name.get(bname))
    }
}

strategy interface

interface BankNameRequest {

        void fetch(String name)

}

implementation class

@Component
class SBIService implements BankNameRequest {

    @Autowired
    private KafkaService kafkaService

    @Override
    void fetch(String name) {
       kafkaService.queue(name)
    }
}

kafka servcie class

@Service
class KafkaService {

    @Autowired
    private KafkaTemplate<String, byte[]> kafkaTemplate

    void queue(String name) {
        //impl
    }
}

here kafkaService is getting null. How can i autowire this kafka service?

Aucun commentaire:

Enregistrer un commentaire