javacdiweld

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?


Solution

  • Note that Weld already makes the command-line arguments available for injection.