Spring IoC概述

被刻印的时光 ゝ 提交于 2020-02-04 09:08:25

1.Spring是什么

Spring是一个企业级开发框架,软件设计层面的框架,优势在于可以将应用程序进行分层,开发者可自主选择组件。
MVC可选:Struts2,Spring MVC
ORMapping可选:Hibernate,MyBats,Spring Data

在这里插入图片描述

Spring框架两大核心机制
IoC(控制反转)/DI(依赖注入)
AOP(面向切面编程)
Spring IoC
在这里插入图片描述

2.如何使用IoC?

1.创建maven工程,添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>aispringioc</artifactId>
    <version>1.0-SNAPSHOT</version>

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

</project>

使用IoC容器的时候,实际上就是创建一个上下文对象
2.创建实体类

@Data
public class Student {

    private long id;
    private String name;
    private int age;
}
  • 传统开发方式:手动去new
 public static void main(String[] args) {
        Student student=new Student();
        student.setId(123);
        student.setName("李四");
        student.setAge(18);
        System.out.println(student);
    }

通过IoC创建对象,在配置文件中添加需要管理的对象

<?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="student" class="com.southwind.entity.Student">
        <property name="id" value="1"></property>
        <property name="age" value="18"></property>
        <property name="name" value="李四"></property>
    </bean>
</beans>

从IoC中获取对象

 ApplicationContext applicationContext=new ClassPathXmlApplicationContext("spring.xml");
        Student student =(Student) applicationContext.getBean("student");
        System.out.println(student);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!