IoC入门案例
步骤
①∶导入Spring坐标
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
②∶定义Spring管理的类(接口),并实现
public interface BookService {
public void save( ) ;
}
public class BookServiceImpl implements BookService {
private BookDao bookDao = new BookDaoImpl();
public void save() {
bookDao. save();
}
}
③∶创建Spring配置文件,配置对应类作为Spring管理的bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http:/ /www.springframework.org/schema/beans"
xmlns :xsi="http:// www . w3.org/20日1/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/be
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="bookService" class="com.itheima. service.impl.BookServiceImpl"></bean>
</beans>
注意事项
bean定义时id属性在同一个上下文中不能重复
④∶初始化IoC容器( Spring核心容器/Spring容器),通过容器获取bean
public class App {
publicistatic void main(String[] args) {
//加载配置文件得到上下文对象,也就是容器对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");//获取资源
BookService bookService = (BookService) ctx.getBean("bookService");
bookService.save();
}
}