Currently, I have a component that implements CommandLineRunner
and parses the command line arguments with Commons CLI.
java -jar app.jar --host 123.123.222 --port 8080
There is also another component, Requester
, which depends on (a subset of) those arguments.
@Component
public class Requester
{
// host and port need to be configured once
private final String host;
private final int port;
public Requester(String host, int port)
{
this.host = host;
this.port = port;
}
public boolean doRequest(String name) throws Exception
{
String url = "http://" + host + ":" + port + "/?command=" + name;
URL obj = new URL(url);
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
int responseCode = connection.getResponseCode();
return 200 == responseCode;
}
}
What can I do to autowire a configured Requester
into future components? What is the Spring way to create parameterized, singleton beans?
One solution would be to have every component, that has any dependency on the program arguments, implement CommandLineRunner
. This way it could parse the program arguments itself, but that is a highly redundant approach. There must be a better solution.