Spring IoC概述

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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值