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.setInp开发者_如何学运维utStream(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.
Use <util:constant ... />
:
<util:constant id = "out" static-field="java.lang.System.out" />
I'm not sure that you can explicitly create a bean using System.out
(which I think is what you're asking). However you can create a bean that uses a factory class / method to return an object (in this case System.out
)
<bean id="streamOut" class="examples.StreamFactory"
factory-method="getSystemOut"/>
精彩评论