03_实现DI(注入依赖)

Bean包

AnimalDao.java

  1. package com.cq.dao;
  2. public class AnimalDao {
  3. public void add(){
  4. System.out.println("dao---------add----------");
  5. }
  6. public AnimalDao() {
  7. System.out.println("dao---------constructor---------");
  8. }
  9. }

AnimalService.java

  1. package com.cq.service;
  2. import com.cq.dao.AnimalDao;
  3. public class AnimalService {
  4. private AnimalDao animalDao; //不能new对象
  5. public AnimalService(AnimalDao animalDao) {
  6. this.animalDao = animalDao;
  7. }
  8. public AnimalService() {
  9. }
  10. public void add(){
  11. animalDao.add();
  12. System.out.println("service---------add----------");
  13. }
  14. public AnimalDao getAnimalDao() {
  15. return animalDao;
  16. }
  17. public void setAnimalDao(AnimalDao animalDao) {
  18. this.animalDao = animalDao;
  19. }
  20. }

方法1: set方法注入

DI.xml

  1. <bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
  2. <bean id="animalService" class="com.cq.service.AnimalService">
  3. <!-- 使用set方法注入属性值 -->
  4. <property name="animalDao" ref="animalDao"></property>
  5. </bean>

Test.java

  1. @Test
  2. public void test02(){
  3. ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
  4. AnimalService animalService = (AnimalService) ac.getBean("animalService");
  5. animalService.add();
  6. }

方法2: 构造方法注入

DI.xml

  1. <bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
  2. <bean id="animalService2" class="com.cq.service.AnimalService">
  3. <!-- 使用构造方法注入属性值 -->
  4. <constructor-arg name="animalDao" ref="animalDao"></constructor-arg>
  5. </bean>

Test.java

  1. @Test
  2. public void test02(){
  3. ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
  4. AnimalService animalService2 = (AnimalService) ac.getBean("animalService2");
  5. animalService2.add();
  6. }

方法3: byName注入

DI.xml

  1. <bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
  2. <!-- 查询与属性名相同的容器中的对象,属性名相同 -->
  3. <bean id="animalService3" class="com.cq.service.AnimalService" autowire="byName"> </bean>

Test.java

  1. @Test
  2. public void test02(){
  3. ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
  4. AnimalService animalService3 = (AnimalService) ac.getBean("animalService3");
  5. animalService3.add();
  6. }

方法4: byType注入(对象唯一)

DI.xml

  1. <bean id="animalDao" class="com.cq.dao.AnimalDao"></bean>
  2. <!-- 查询与属性值相同类型的容器中的对象,但是要求类型相同的对象唯一,否则抛出异常,不知道用哪个匹配 -->
  3. <!-- 弊端:Dao的对象只能有一个 -->
  4. <bean id="animalService4" class="com.cq.service.AnimalService" autowire="byType"> </bean>

Test.java

  1. @Test
  2. public void test02(){
  3. ApplicationContext ac = new ClassPathXmlApplicationContext("DI.xml");
  4. AnimalService animalService4 = (AnimalService) ac.getBean("animalService4");
  5. animalService4.add();
  6. }