Previous we see how to do Setter injection:https://www.cnblogs.com/answer1215/p/9472117.html
Now let's see how to cover Setter injection to coustructor injection. Notice, don ' t need to compare which one are better, you can use both.
Different from setter injection which use ' name ', constructor injection using ' index '.
Applicationcontext.xml
<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "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.xsd" > <!--Define A class, using implementation - <Beanname= "Foo"class= "Com.pluralsight.repository.HibernateCustomerRepositoryImpl"></Bean> <!--Setter injection:inject Hibernatecustomerrepositoryimpl to Customerrepository - <Beanname= "CustomerService"class= "Com.pluralsight.service.CustomerServiceImpl"> <!--<property name= "customerrepository" ref= "foo" ></property> - <constructor-arg index= "0" ref= "foo"> </constructor-arg> </Bean></Beans>
PackageCom.pluralsight.service;ImportCom.pluralsight.model.Customer;Importcom.pluralsight.repository.CustomerRepository;Importjava.util.List; Public classCustomerserviceimplImplementsCustomerService {//private Customerrepository customerrepository = new Hibernatecustomerrepositoryimpl (); Privatecustomerrepository customerrepository; Public Customerserviceimpl () {} public Customerserviceimpl (customerrepository Customerrepository) { this. customerrepository = customerrepository; }/*Public void Setcustomerrepository (Customerrepository customerrepository) {this.customerrepository = Custom Errepository; }*/@Override PublicList<customer>FindAll () {returnCustomerrepository.findall (); }}
[Java Sprint] Spring XML Configuration:constructor Injection Demo