Java Reference
In-Depth Information
Constructor Injection
In this strategy, the dependent object is passed as part of the constructor call, as shown in
Listing 2-10.
Listing 2-10. CarServiceImpl.java with Constructor Injection
public class CarServiceImpl implements CarService{
private CarDao carDao;
public void CarServiceImpl (CarDao carDao){
this.carDao = carDao;
}
public void refuel(Car car){
carDao.updateFuelConsumed(car) ;
}
}
To achieve constructor injection, you need to alter the configuration as well, as
depicted in Listing 2-11.
Listing 2-11. spring-config.xml with Constructor Injection
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=" http://www.springframework.org/schema/beans"
xmlns:xsi=" http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"
>
<bean name="carDao"
class="com.apress.simpleapp.dao.CatDaoImpl" />
<bean name="carService"
class="com.apress.simpleapp.service.CarServiceImpl">
<constructor-arg>
<ref bean="carDao"/>
</constructor-arg>
</beans>
 
Search WWH ::




Custom Search