DI 依赖注入
依赖:一个对象需要使用另一个对象
注入:通过set方法进行另一个对象的设置
实例:
创建bookDao
package b.di; public interface BookDao { public void addBook(); }
创建bookDaoImpl
package b.di; public class BookDaoImpl implements BookDao { @Override public void addBook() { System.out.println("di 添加 BOOK"); } }
创建bookservice
package b.di; public interface BookService { void save(); void AddBook(); }
创建bookServiceImpl
package b.di; public class BookServiceImpl implements BookService { //方式1:接口=实现类 // private BookDao bookdao=new BookDaoImpl(); //方式2:接口+setter private BookDao bookDao; public void setBookDao(BookDao bookDao) { this.bookDao = bookDao; } /* (non-Javadoc) * @see b.di.BookService#addBook() */ @Override public void save(){ System.out.println("this is save "); } @Override public void AddBook() { bookDao.addBook(); } }
创建测试类
package b.di; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestDi { @Test public void demo1(){ String xmlPath="b/di/beans.xml"; ApplicationContext appContext=new ClassPathXmlApplicationContext(xmlPath); BookService bookService=(BookService) appContext.getBean("BookServiceId"); bookService.save(); } @Test public void demo2(){ String xmlPath="b/di/beans.xml"; ApplicationContext appContext=new ClassPathXmlApplicationContext(xmlPath); BookService bookService=(BookService) appContext.getBean("BookServiceId"); bookService.AddBook(); } }
创建xml配置文件
<?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"> <!-- 配置service <bean> 配置需要创建的对象 id :用于之后从spring容器获得实例时使用的 class :需要创建实例的全限定类名 <bean id="UserServiceId" class="a.ioc.UserserviceImpl"></bean>--> <!-- 创建service --> <bean id="BookServiceId" class="b.di.BookServiceImpl"> <property name="BookDao" ref="BookDaoImplId"></property> <!-- property 用于进行属性注入的 name 是属性名 ref:另一个beanid值得引用 --> </bean> <!-- 创建Dao --> <bean id="BookDaoImplId" class="b.di.BookDaoImpl"></bean> </beans>
现在就可以跑测试用例了
demo1 的运行结果
demo2的运行结果