一、DI案例思路
1.基于ioc管理
2.services 中是通过new的方式创建的Dao对象不能保留
3.Serices中需要的Dao对象如何进入到Serives中?(提供方法:最简单的是提供一个set方法)
4.serives与Dao之间的关系如何描述?(配置)
二、DI的运用
原始的未使用DI方式 逻辑层调用数据层
使用DI思想降低耦合度
三、源代码
BookDao接口
package com.itheima.dao;
public interface BookDao {
public void save1();
}
BookDaoImpl类
package com.itheima.dao.impl;
import com.itheima.dao.BookDao;
public class BookDaoImpl implements BookDao {
@Override
public void save1() {
System.out.println("bookdao save-----");
}
}
BookServices接口
package com.itheima.serives;
public interface BookServices {
public void save2();
}
BookSerivesImpl类
package com.itheima.serives.impl;
import com.itheima.dao.BookDao;
import com.itheima.dao.impl.BookDaoImpl;
import com.itheima.serives.BookServices;
public class BookSerivesImpl implements BookServices {
// 提供对应的set方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
//删除业务层使用new的方式创建的dao 对象
private BookDao bookDao;
@Override
public void save2() {
// 逻辑层调用数据层
bookDao.save1();
System.out.println("bookserives dao");
}
}
applicationContext.xml文件
package com.itheima;
import com.itheima.dao.BookDao;
import com.itheima.serives.BookServices;
import com.itheima.serives.impl.BookSerivesImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
public static void main(String[] args) {
// 加载ioc容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
// 根据传入的id在ioc容器中获取相应的bean
BookSerivesImpl bookSerives = (BookSerivesImpl) ac.getBean("bookSerives");
bookSerives.save2();
}
}
App1入口类
package com.itheima;
import com.itheima.dao.BookDao;
import com.itheima.serives.BookServices;
import com.itheima.serives.impl.BookSerivesImpl;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class App1 {
public static void main(String[] args) {
// 加载ioc容器
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
// 根据传入的id在ioc容器中获取相应的bean
BookSerivesImpl bookSerives = (BookSerivesImpl) ac.getBean("bookSerives");
bookSerives.save2();
}
}