1.Spring概述
2.Spring Framework系统架构图
3.核心概念
4.IoC的使用
- 导入spring-context的坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.22.RELEASE</version>
</dependency>
- 创建Spring配置文件,配置bean
<bean id="bookDao" class="com.my.dao.impl.BookDaoImpl"/>
<bean id="bookService" class="com.my.service.impl.BookServiceImpl"/>
</beans>
- 获取IoC容器,获取bean
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationConfig.xml");
BookDao bookDao = (BookDao) context.getBean("bookDao");
bookDao.save();
BookService bookService = (BookService) context.getBean("bookService");
bookService.save();
}
5.DI的使用
- 删除使用new的形式创建的对象
private BookDao bookDao;
- 提供依赖对象对应的setter方法
public void setBookDao(BookDao bookDao) {
this.bookDao = bookDao;
}
- 配置service与dao之间的依赖关系
<bean id="bookDao" class="com.my.dao.impl.BookDaoImpl"/>
<bean id="bookService" class="com.my.service.impl.BookServiceImpl">
<property name="bookDao" ref="bookDao"/>
</bean>
- 获取IoC容器,获取bean
public static void main(String[] args) {
ApplicationContext context=new ClassPathXmlApplicationContext("applicationConfig.xml");
BookDao bookDao = (BookDao) context.getBean("bookDao");
bookDao.save();
BookService bookService = (BookService) context.getBean("bookService");
bookService.save();
}
|