When I'm writing a Spring command line application which parses command line arguments, how do I pass them to Spring? Would I want to have my main() structured so that it first parses the command line args and then inits Spring? Even so, how would it pass the object holding the parsed args to Spring?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Consider the following class:
along with:
Here is an example to boot strap spring for a Main method, simply grab the passed params as normal then make the function you call on your bean (in the case deployer.execute()) take them as Strings or via any format you feel suitable.
Starting from Spring 3.1 there is no need in any custom code suggested in other answers. Check CommandLinePropertySource, it provides a natural way to inject CL arguments into your context.
And if you are a lucky Spring Boot developer you could simplify your code one step forward leveraging the fact that SpringApplication gives you the following:
And if you are interested in the Spring Boot property resolution order please consult this page.
You can also pass an Object array as a second parameter to
getBean
which will be used as arguments to the constructor or factory.Have a look at my Spring-CLI library - at http://github.com/sazzer/spring-cli - as one way of doing this. It gives you a main class that automatically loads spring contexts and has the ability to use Commons-CLI for parsing command line arguments automatically and injecting them into your beans.
Two possibilities I can think of.
1) Set a static reference. (A static variable, although typically frowned upon, is OK in this case, because there can only be 1 command line invocation).
You can then reference the command line arguments in Spring via:
Alternatively (if you are completely opposed to static variables), you can:
2) Programmatically add the args to the application context:
Parsing the command line arguments is left as an exercise to the reader.