1. 程式人生 > >Spring第一課:依賴注入DI(二)

Spring第一課:依賴注入DI(二)

      DI Dependency Injection ,依賴注入

       is a :是一個,繼承。

       has a:有一個,成員變數,依賴。

              class B {

           private A a;   //B類依賴A類

        }

       依賴:一個物件需要使用另一個物件

       注入:通過setter方法進行另一個物件例項設定。

 例如:

       class BookServiceImpl{

              //之前開發:介面 = 實現類  (service和dao耦合)

              //private BookDao bookDao = new BookDaoImpl();

             //spring之後 (解耦:service實現類使用dao介面,不知道具體的實現類)

              private BookDao bookDao;

              setter方法

   }

    模擬spring執行過程

       建立service例項:BookService bookService = new BookServiceImpl()      -->IoC  <bean>

       建立dao例項:BookDao bookDao = new BookDaoImple()                          -->IoC

       將dao設定給service:bookService.setBookDao(bookDao);                         -->DI   <property>

BookDao

package com.b_di;

public interface BookDao {
	boolean addBook();
}

BookDaoImpl

package com.b_di;

public class BookDaoImpl implements BookDao {

	@Override
	public boolean addBook() {
		System.out.println("add book");
		return false;
	}

}

BookService

package com.b_di;

public interface BookService {
	boolean addBook();
}
package com.b_di;

public class BookServiceImpl implements BookService {

	private BookDao bookDao;
	
	public void setBookDao(BookDao bookDao) {
		this.bookDao = bookDao;
	}

	@Override
	public boolean addBook() {
		return this.bookDao.addBook();
	}
	
}

 配置檔案,和類同在一個包塊下面:

<?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.xsd">

	<!-- 建立BookService -->
	<bean id="bookService" class="com.b_di.BookServiceImpl">
		<!-- 
		property標籤:
			name: bean的屬性名,通過setter方法獲得的;
				setBookDao -> 去掉set:BookDao -> 首字母變成小寫:bookDao
			ref:另一個bean的id值的引用 
		為bookService注入bookDao
		 -->
		<property name="bookDao" ref="bookDao"></property>
	</bean>
	
	<!-- 建立BookDao -->
	<bean id="bookDao" class="com.b_di.BookDaoImpl"></bean>
</beans>

測試依賴注入是否成功:

package com.b_di;

import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestDI {

	@Test
	public void testInjectionDependence() {
		String xmlPath = "com/b_di/beans.xml";
		ApplicationContext applicationContext = (ApplicationContext) new ClassPathXmlApplicationContext(xmlPath);
		
		BookService bookService = (BookService) applicationContext.getBean("bookService");
		bookService.addBook();
	}
}