I am trying to implement the strategic pattern,the problem is that I could not access any dependency injected inside the strategy implmentation classes, so here is my code
Payment strategy interface
public interface PaymentStrategy {
public void processPayment(double amount);
}
Payment strategy interface implementation
@ApplicationScoped
public class CreditCardStrategy implements PaymentStrategy {
@Inject
@RestClient
ApiExample apiExample
public void processPayment(double amount) {
apiExample.doSomething() **//NULL POINTER EXCEPTION**
// Process credit card payment
}
}
@ApplicationScoped
public class PayPalStrategy implements PaymentStrategy {
@Inject
Service service
public void processPayment(double amount) {
service.doSomething() **//NULL POINTER EXCEPTION**
// Process PayPal payment
}
}
Payment strategy factory
public class PaymentStrategyFactory {
public PaymentStrategy getPaymentStrategy(String paymentMethod) {
if (paymentMethod.equals("creditcard")) {
return new CreditCardStrategy();
} else if (paymentMethod.equals("paypal")) {
return new PayPalStrategy();
} else {
throw new IllegalArgumentException("Invalid payment method: " + paymentMethod);
}
}
}
Main program method
String paymentMethod = "creditcard"; // Or "paypal"
PaymentStrategyFactory factory = new PaymentStrategyFactory();
PaymentStrategy paymentStrategy = factory.getPaymentStrategy(paymentMethod);
PaymentProcessor paymentProcessor = new PaymentProcessor(paymentStrategy);
paymentProcessor.processPayment(100.0); //NULL POINTER EXCEPTION CAUSED BY apiExample.doSomething()
To expand on the answer given in the comments, here's how you might get the bean from the context in spring. Here's a quarkus example of how you might do this.
it prints: