目录
知识点
- DI (Dependency Injection)依赖注入
- Is a :继承
- has a:成员变量,依赖
class B{
private A; //B依赖于A
}
- 依赖:一个对象需要使用另一个对象
- 注入:通过setter方法进行另一个对象定例设置
class BookServiceImpl{
//之前开发,接口=实现类(Service和Dao耦合)
private BookDao bookDao=new BookDaoImpl();
//Spring之后(解耦:service实现类使用dao接口,不知道具体的实现类)
private BookDao bookDao;
stter方法
}
模拟spring执行过程
创建service实例:BookService bookService=new BookserviceImpl(); IOC <bean>
创建dao实例:BookDao bookDao=new BookDaoImpl(); IOC
将dao设置给service: bookService.setBookDao() DI <property>
目标类
- 创建BookService接口和实现类
- 创建BookDao接口和实现类
- 将Dao和Service配置到xml文件
- 使用api测试
代码
1.项目结构
2.BookDao.java
package com.tjnu.b_di;
public interface BookDao {
public void addBook();
}
3.BookDaoImpl.java
package com.tjnu.b_di;
public class BookDaoImpl implements BookDao {
@Override
public void addBook() {
System.out.println("dao add book!");
}
}
4.BookService.java
package com.tjnu.b_di;
public interface BookService {
public void addBook();
}
5.BookServiceImpl.java
package com.tjnu.b_di;
public class BookServiceImpl implements BookService {
//方式一:接口=实现类
//private BookDao bookdao=new bookDaoImpl();
//方式二:接口+setter方法
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
@Override
public void addBook() {
this.bookDao.addBook();
}
}
6.applicationContext.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">
<!-- bean definitions here 模拟spring执行过程 创建service实例:BookService bookService=new
BookServiceImpl(); IOC bean 创建dao实例:BookDao bookDao=new BookDaoImpl(); IOC
将dao设置给service:bookService.setBookDao(bookDao); DI property
property用于进行属性注入
name:bean的属性名,通过setter方法获得 setBookDao ##>BookDao ##>bookDao
ref:另一个bean的id值的引用
-->
<!-- 创建service -->
<bean id="bookServiceId"
class="com.tjnu.b_di.BookServiceImpl">
<property name="bookDao" ref="bookDaoId"></property>
</bean>
<!-- 创建dao -->
<bean id="bookDaoId"
class="com.tjnu.b_di.BookDaoImpl"></bean>
</beans>
7.testDi.java
package com.tjnu.b_di;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class testDi {
@Test
public void demo01() {
//从spring容器中获得
String xmlPath="com/tjnu/b_di/applicationContext.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
BookService bookservice=(BookService)applicationContext.getBean("bookServiceId");
bookservice.addBook();
}
}
遇到的问题
运行测试代码testDi.java时代码报错
Spring报错: org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class [xxx]
如下图:
然后当时我的xml文件内容是如下图:
问题出在class路径那(光标在的位置)加上了.java,去掉就好了。