IoC入门案例

1.管理什么?(Service和Dao)

2.如何将被管理的对象告知IoC容器?(配置)

3.被管理的对象交给IoC容器,如何获取IoC容器?(接口)

4.IoC容器得到后,如何从容器中获取到bean?(接口方法)

5使用Spring导入哪些坐标?(pom.xml)

快速入门:

1.配置坐标

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.2.1.RELEASE</version>
</dependency>

2.配置文件:

<?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的坐标-->
    <!--2.配置bean-->
    <bean id="bookDao" class="org.example.dao.impl.BookDaoImpl"/>
    <bean id="bookService" class="org.example.service.impl.BookServiceImpl"/>
</beans>

3.初始化容器,通过容器获取bean


import org.example.dao.BookDao;
import org.example.service.BookService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

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();

    }
}
posted @ 2023-02-15 19:59  会秃头的小白  阅读(16)  评论(0编辑  收藏  举报