Spring IoC 入门案例步骤

发布时间 2024-01-02 16:37:32作者: belhomme

步骤

  1. 导入 Spring 坐标
<!-- pom.xml文件,配置maven环境 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.10.RELEASE</version>
</dependency>
  1. 定义 Spring 管理的类(接口)
public interface BookService {
    public void save();
}
public class BookServiceImpl implements BookService {
    private BookDao bookDao = new BookDaoImpl();

    @Override
    public void save() {
        System.out.println("book service save...");
        bookDao.save();
    }
}
  1. 创建 Spring 配置文件,配置对应类作为 Spring 管理的 bean
<!-- 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 id="bookDao" class="com.bellongyan.dao.impl.BookDaoImpl"/>
    <bean id="bookService" class="com.bellongyan.service.impl.BookServiceImpl"/>

</beans>
  1. 初始化 IoC 容器(Spring核心容器/Spring容器),通过容器获取 bean
public class App2 {
    public static void main(String[] args) {
//        获取IOC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

//        获取bean
        BookDao bookDao = (BookDao) ctx.getBean("bookDao");
        bookDao.save();

        BookService bookService = (BookService) ctx.getBean("bookService");
        bookService.save();

    }
}