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();
}
}