Injection Types
Constructor Type Injection
ThepublicclassSubclassimplementsSuper{privateStringfHost=null;privateintfPort=0;publicSubclass(StringfHost,intfPort){this.fHost=fHost;this.fPort=fPort;}@OverridepublicStringread(){// your impl goes herereturnnull;}}
fHost and fPort
arguments are then wired using
constructor-arg attributes defined in the XML config file:
name="reader" class="com.test.Subclass">
value="test.com" />
value="1040" />
You can set references to other beans, too via the constructor arguments.
This is how thename="readerService"class="com.test.ReaderService">ref="reader"/>name="reader"class="com.test.Subclass">value="src/main/resources/basics/basics-trades-data.txt"/>
ReaderService will look with a constructor accepting
an IReader type:public class ReaderService {private IReader reader = null;public ReaderService(IReader reader) {this.reader = reader;
}
...
}Argument type resolution
name="reader" class="com.test.Subclass">
type="String" value="test.com" />
type="int" value="1040" />
The types are normal Java types—such as int,
boolean, double, String, and so
on.You could also set index’s on the values, starting the index from zero as shown here:
name="reader" class="com.test.Subclass">
index="0" type="String" value="test.com" />
index="1" type="int" value="1040" />
Setter Type Injection
In order to use the setter injection, we have to provide setters on the
respective variables. If the property exhibits read and write
characteristics, provide both a setter and a getter on the
variable.
The significant points are the the setter and getter methods on thepublicclassReaderService{privateIReaderreader=null;// Setter and getterpublicvoidsetReader(IReaderreader){this.reader=reader;}publicIReadergetReader(){returnreader;}...}
IReader variable and the omission of the constructor altogether.
The configuration of the class in our XML file looks like this:name="readerService"class="com.test.ReaderService">name="reader"ref="reader"/>name="reader"class="com.test.Subclass">...
We can mix the injection types as we like .
name="reader"
class="........">
value="src/main/resources/basics/basics-trades-data.txt" />
name="componentName" value="TradeFileReader"/>