03_实现DI(注入依赖)
Bean包
AnimalDao.java
package com.cq.dao;
public class AnimalDao {
public void add(){
System.out.println("dao---------add----------");
}
public AnimalDao() {
System.out.println("dao---------constructor---------");
}
}
AnimalService.java
package com.cq.service;
import com.cq.dao.AnimalDao;
public class AnimalService {
private AnimalDao animalDao; //不能new对象
public AnimalService(AnimalDao animalDao) {
this.animalDao = animalDao;
}
public AnimalService() {
}
public void add(){
animalDao.add();
System.out.println("service---------add----------");
}
public AnimalDao getAnimalDao() {
return animalDao;
}
public void setAnimalDao(AnimalDao animalDao) {
this.animalDao = animalDao;
}
}
方法1: set方法注入
DI.xml
<bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
<bean id="animalService" class="com.cq.service.AnimalService">
<!-- 使用set方法注入属性值 -->
<property name="animalDao" ref="animalDao"></property>
</bean>
Test.java
@Test
public void test02(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
AnimalService animalService = (AnimalService) ac.getBean("animalService");
animalService.add();
}
方法2: 构造方法注入
DI.xml
<bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
<bean id="animalService2" class="com.cq.service.AnimalService">
<!-- 使用构造方法注入属性值 -->
<constructor-arg name="animalDao" ref="animalDao"></constructor-arg>
</bean>
Test.java
@Test
public void test02(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
AnimalService animalService2 = (AnimalService) ac.getBean("animalService2");
animalService2.add();
}
方法3: byName注入
DI.xml
<bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
<!-- 查询与属性名相同的容器中的对象,属性名相同 -->
<bean id="animalService3" class="com.cq.service.AnimalService" autowire="byName"> </bean>
Test.java
@Test
public void test02(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
AnimalService animalService3 = (AnimalService) ac.getBean("animalService3");
animalService3.add();
}
方法4: byType注入(对象唯一)
DI.xml
<bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
<!-- 查询与属性值相同类型的容器中的对象,但是要求类型相同的对象唯一,否则抛出异常,不知道用哪个匹配 -->
<!-- 弊端:Dao的对象只能有一个 -->
<bean id="animalService4" class="com.cq.service.AnimalService" autowire="byType"> </bean>
Test.java
@Test
public void test02(){
ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
AnimalService animalService4 = (AnimalService) ac.getBean("animalService4");
animalService4.add();
}