IoC入门案例(XML版)

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 BookDao();
    public void save() {
        System.out.println("book service 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/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <!--1.导入spring的坐标spring-context,对应版本是5.2.10.RELEASE-->
<bean id="bookService" class="com.itheima.service.impl.BookServiceImpl"> </bean> </beans>

④:初始化IoC容器(Spring核心容器/Spring容器),通过容器获取bean

    public static void main(String[] args) {
        //3.获取IoC容器
        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        BookService bookService = (BookService) ctx.getBean("bookService");
        bookService.save();

    }

  

posted @ 2023-02-01 16:42  __破  阅读(20)  评论(0)    收藏  举报