一、自动装配
1.1、BookDao接口和实现类
public interface BookDao {
void save();
}
public class BookDaoImpl implements BookDao {
public void save(){
System.out.println("book dao save......");
}
}
1.2、BookService接口和实现类
public interface BookService {
void save();
}
public class BookServiceImpl implements BookService {
private BookDao bookDao;
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
public void save(){
bookDao.save();
}
}
1.3、配置文件
<?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 id="bookDao" class="com.itheima.dao.impl.BookDaoImpl" ></bean>
<bean id="bookService" name="service" class="com.itheima.service.impl.BookServiceImpl" autowire="byType"></bean>
</beans>
1.4、使用方法
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
BookService bookService = (BookService) ctx.getBean("service");
bookService.save();
}
1.5、总结
- 在配置文件中添加autowire属性为byType
- spring会按照BookDao类型找到对应的Bean实现注入
文章来源地址https://www.toymoban.com/news/detail-604502.html
文章来源:https://www.toymoban.com/news/detail-604502.html
到了这里,关于spring学习笔记七的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!