Search code examples
javaspringdependency-injectionconstructor-injection

Spring: Inject static member (System.in) via constructor


I wrote some sort of console client for a simple application. To be more flexible, I thought it would be nice to only depend on java.io.Input-/OutputStream, instead of accessing System.in/out directly.

I renamed the class ConsoleClient to StreamClient, added setters and made sure that the instance fields are used instead of System.in/out.

At the moment my client code looks like this:

ApplicationContext appCtx = new ClassPathXmlApplicationContext("...");
StreamClient cc = (StreamClient) appCtx.getBean("streamClient");
cc.setInputStream(System.in);
cc.setOutputStream(System.out);
cc.run();   // start client

Question:

Is there a way to move lines 3 and 4 into the Spring configuration (preferably constructor injection)?

Thanks for your time.


Solution

  • Use <util:constant ... />:

    <util:constant id = "out" static-field="java.lang.System.out" />