Vladimir
Vladimir

Reputation: 15

How to correctly substitute the @Value from the application context

I've tried to do that, but provider token is NULL though @Value is determined by Spring.

@Slf4j
public class CheckoutHandler {
    private SendInvoice sendInvoice;

    @Value("${providerToken}")
    String providerToken;

Maybe it has something to do with how I initialize the class

CheckoutHandler checkoutHandler = new CheckoutHandler();

Please tell me how to correctly substitute the value from the application context

Upvotes: 1

Views: 502

Answers (2)

Arthur Frade
Arthur Frade

Reputation: 71

But if you really want to create CheckoutHandler instances at runtime, while recovering token data from environment, you can use java System.getProperty(String) method to set the providerToken value. Something like:

public class CheckoutHandler {
    private SendInvoice sendInvoice;
    private static final String providerToken = System.getProperty("providerToken");

    public CheckoutHandler() {}
}

Upvotes: 0

Panagiotis Bougioukos
Panagiotis Bougioukos

Reputation: 19173

Maybe it has something to do with how I initialize the class

CheckoutHandler checkoutHandler = new CheckoutHandler();

Yes

The way you initialize it, it becomes a simple java object of that class. That way spring can not use dependency injection.

If you let Spring create the instance and retrieve it from the application context spring will create an instance of another proxy class and then it would be able to achieve dependency injection using the application context and values that you want.

Just let Spring create it (ex use @Component on CheckoutHandler) and retrieve the instance, whenever you want to use it like

@Component
public class MyClass {

@Autowired
CheckoutHandler checkoutHandler;

public void method1(){
  checkoutHandler.....
}

Upvotes: 1

Related Questions