javaEE架构程序设计-Spring IOC容器

Spring IOC容器

实例方式讲解

  • 项目名称:
    spring01
  1. 引入spring 框架
    引入是 spring-context框架
    pom.xml
    https://search.maven.org/
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>5.1.20.RELEASE</version>
</dependency>
  1. 创建spring配置文件
    applicationContext.xml
    在classpath类路径下创建 xml文件选择spring config
    image
<?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="stu1" class="yzg.kc2021.spring01.Student"></bean>
</beans>

含义: 在spring IOC 容器中创建bean,bean的管理由容器来完成,这种思想就是控制翻转(IOC)

  1. 创建包
    gyh.yogurt.spring01

  2. 创建应用对象

Appication

public class Application {
    public static void main(String[] args) {
        // 1.没有引入sping框架的编程方式
        Student s1 = new Student();
        s1.create();

        // 2.引入spring框架编程方式
        IStudent s2 = null;
        ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
        s2 = (IStudent) ctx.getBean("stu1");
        s2.create();
    }
}

IStudent

public interface IStudent {
    public void create();       // 创建
}

Student

public class Student implements IStudent {

    public void create() {
        System.out.println("学生对象被创建..." + this);
    }
}
  1. 分析
    依赖于springIOC容器的面接口编程的优点

适用于团队开发,解耦

posted @ 2021-03-23 15:48  酸奶面包  阅读(63)  评论(0编辑  收藏  举报