无法访问注入到策略模式实现类中的依赖项

问题描述 投票:0回答:0

我正在尝试实施战略模式,问题是我无法访问战略实施类中注入的任何依赖项,所以这是我的代码

支付策略界面

public interface PaymentStrategy {
    public void processPayment(double amount);
} 

支付策略接口实现

@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
    }
}

支付策略工厂

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);
        }
    }
}

主要程序方法

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()
java dependency-injection strategy-pattern quarkus-rest-client
© www.soinside.com 2019 - 2024. All rights reserved.