Injection Types
Constructor Type Injection
Thepublic
class
Subclass
implements
Super
{
private
String
fHost
=
null
;
private
int
fPort
=
0
;
public
Subclass
(
String
fHost
,
int
fPort
)
{
this
.
fHost
=
fHost
;
this
.
fPort
=
fPort
;
}
@Override
public
String
read
()
{
// your impl goes here
return
null
;
}
}
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 the
name=
"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 thepublic
class
ReaderService
{
private
IReader
reader
=
null
;
// Setter and getter
public
void
setReader
(
IReader
reader
)
{
this
.
reader
=
reader
;
}
public
IReader
getReader
()
{
return
reader
;
}
...
}
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"
/>