简体   繁体   中英

How to pass command line arguments to a weld container?

I have a application which is started via command line like java -jar MyAssembledJarWithAllDep.jar -foo bar

I am using weld.se to be able to use the jakarta ee cdi specification. Furthermore I am using the apache cli tool to parse the comman line arguments.

Here are my maven imports:

        <dependency>
            <groupId>jakarta.enterprise</groupId>
            <artifactId>jakarta.enterprise.cdi-api</artifactId>
            <version>3.0.0</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.jboss.weld.se</groupId>
            <artifactId>weld-se</artifactId>
            <version>2.4.6.Final</version>
        </dependency>

        <dependency>
            <groupId>commons-cli</groupId>
            <artifactId>commons-cli</artifactId>
            <version>1.4</version>
        </dependency>

That's how I initialize the container:

    public static void main(String[] args) {
        Weld weld = new Weld();
        WeldContainer container = weld.initialize();
        container.select(MyRunnerClass.class).get().run(args);
        container.shutdown();
    }

I could do the following:

public void run(String[] args) {
   CommandLineParser clp = new CommandLineParser(args);
   clp.parse();

But since I want to use the full support of cdi, I cannot the object since I created it myself! So how do I pass the arguments to the container so that weld can create the CommandLineParser himself with the needed arguments?

I am not familiar with apache cli tools so I am assuming CommandLineParser is not a bean on its own and you want to turn it into a bean. In that case you need to provide a producer method which can make use of any local metadata in creation of the object.

The following method is a producer method and needs to be placed in another bean class for it to work (see CDI specification for more details):

@Produces
@ApplicationScoped // or any other scope that you want to use for the bean!
public CommandLineParser produceCmdLineParser() {
  String[] args = retrieveArgs(); // grab arguments from your main class or other place
  return new CommandLineParser(args);
}

The above producer method will then be invoked by Weld (do not invoke it manually) when you ask the CDI container for bean of type CommandLineParser via standard or dynamic injection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM