1

I have created a Java library that I want to call from Spring applications. The library has some @Value parameters, which are to be populated from system variables that we pass in to the calling application via -D arguments. In addition, it has an @EnableConfigurationProperties that points to some Autowired configuration beans.

However when I call the library from a consumer application with the appropriate system variables supplied, the Spring @Value parameters do not get populated, and the beans do not get wired; they all come up null.

How can I inject the system variables from the consumer application into the Spring library classes?

Here is the main library code: enter image description here

Here is the library configuration class enter image description here

Vinny Gray
  • 477
  • 5
  • 18
  • I would prefer code to be posted as text, not images. Better for searching, better for copying stuff to try things out. Also, _my_ colours, not yours. – Michael Piefel Jun 07 '21 at 19:15

1 Answers1

0

Spring has support for Environment.

Injecting Environment bean

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyEnvironment{
 
    @Autowired
    private Environment env;
 
    public String getProp() {
        return env.getProperty("my.app.prop");
    }
}

Implement EnvironmentAware

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public class MyEnvironment implements EnvironmentAware {
 
    private String prop;
 
    @Override
    public void setEnvironment(Environment env) {
        this.prop= env.getProperty("my.app.prop);
    }
 
    public String getProp() {
        return prop;
    }
 
    public void setProp(String prop) {
        this.prop= prop;
    }
}
Ankur Singhal
  • 26,012
  • 16
  • 82
  • 116
  • Sorry, not sure if this is solving the problem. I am already passing the arguments into the calling application as -D parameters. Where should I add the EnvironmentAware, is that in the caller or the library? And why am I returning just one property in MyEnvironment, where do I put the other ones? To repeat, the problem was that the library class was not picking up the @Value values from the -D parameters I pass in to the caller. – Vinny Gray Jun 07 '21 at 17:52
  • @VinnyGray Could you post the code for internal librray, as how it is picking the variable ? Also the command line you are providing ? Does [this](https://stackoverflow.com/questions/51079036/how-to-access-a-property-passed-by-command-line-in-spring-boot) helps you. – Ankur Singhal Jun 07 '21 at 18:01