1

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

Vladimir
  • 15
  • 3
  • use `@Component` under `@Slf4j`. It need to be a spring component to be able to inject values – Panagiotis Bougioukos May 20 '21 at 15:02
  • The `@Value` annotation will only work for spring instantiated beans not with the ones created by the `new` keyword. https://stackoverflow.com/questions/4130486/spring-value-annotation-always-evaluating-as-null – madteapot May 20 '21 at 15:02
  • I've tried to use @Component but it also dosen't work – Vladimir May 20 '21 at 15:07

2 Answers2

1

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.....
}
Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47
0

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() {}
}