Previous we have seen Constructore injection:https://www.cnblogs.com/answer1215/p/9484872.html
It would is easier to using autowire to reduce the code, and Autowite have four different types:
- Bytype
- ByName
- Constructor
- No
First let's see how to use ' autowire= ' constructor "':
<name= "CustomerService" class= " Com.pluralsight.service.CustomerServiceImpl " autowire=" constructor "> <!--- </beans>
We comment out constructor injection and using Autowire.
ByName:
PackageCom.pluralsight.service;ImportCom.pluralsight.model.Customer;Importcom.pluralsight.repository.CustomerRepository;Importjava.util.List; Public classCustomerserviceimplImplementsCustomerService {//private Customerrepository customerrepository = new Hibernatecustomerrepositoryimpl (); Privatecustomerrepository customerrepository; PublicCustomerserviceimpl () {} PublicCustomerserviceimpl (customerrepository customerrepository) { This. Customerrepository =customerrepository; } //if set autowire by name, so in ApplicationContext <bean name= "customerrepository": >//if <bean name= "foo". > Then this function should is rename public void Setfoo (Customerrepository customerrepository) Public voidsetcustomerrepository (customerrepository customerrepository) { This. Customerrepository =customerrepository; } @Override PublicList<customer>FindAll () {returnCustomerrepository.findall (); }}
<?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 - <Bean name= "Customerrepository" class= " Com.pluralsight.repository.HibernateCustomerRepositoryImpl "></bean> <!--Setter injection:inject Hibernatecustomerrepositoryimpl to Customerrepository - <Beanname= "CustomerService"class= "Com.pluralsight.service.CustomerServiceImpl" autowire= "ByName" > <!--<property name= "customerrepository" ref= "foo" ></property> - <!--<constructor-arg index= "0" ref= "foo" ></constructor-arg> - </Bean></Beans>
Bytype:
<Beanname= "CustomerService"class= "Com.pluralsight.service.CustomerServiceImpl" autowire= "Bytype" > <!--<property name= "customerrepository" ref= "foo" ></property> - <!--<constructor-arg index= "0" ref= "foo" ></constructor-arg> - </Bean>
It doesn ' t matter we use ' name= ' customerservice ' or ' name= ' foo ', because it finding by type, so still'll work.
[Java Sprint] Autowire