- Spring 是一个开源免费的框架(容器)
- Spring是一个轻量级的,非入侵式的框架
- 控制反转(IOC),面向切面(AOP)
一句话:Spring就是一个轻量级的控制反转和面向切面的框架。
IOC本质:
控制反转是一种设计思想,DI(dependences in 依赖注入)是实现IOC的以一种方法。
没有IOC的程序中,我们使用面向对象编程,对象的创建与对象之间的依赖关系完全硬编码在程序中,对象的创建由程序自己控制,控制反转后将对象的创建转移给第三方,所谓的控制反转即:获得依赖对象的方式反转了。
采用xml方式配置的时候,Beans的定义信息和实现是分离的,而采用注解可以把两者结合在一起,Beans的定义信息直接以注解的方式定义在实现类中,从而达到零配置的目的。
控制反转是一种通过描述(xml或注解)并通过第三方去生产或者获取特定对象的方式。在Spring中实现控制反转的是IOC容器,其实现方法是依赖注入。
Spring简单使用:
先添加Spring依赖:
<!-- Spring 依赖-->
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
</dependencies>
存在如下Dao层和业务层:
UserDaoImpl和UserMysqlImpl都实现UserDao接口
package com.tt.dao;
public interface UserDao {
void getUser();
}
业务层接口:
package com.tt.service;
public interface UserService {
void getUser();
}
业务层实现:
在resources目录下编写Beansxml:
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userDaoImpl" class="com.tt.dao.UserDaoImpl"/>
<bean id="mysqlImpl" class="com.tt.dao.UserMysqlImpl"/>
<bean id="userService" class="com.tt.service.UserServiceImpl">
<!--
ref:引用Spring容器中创建好的对象
value:具体的值,基本数据类型
-->
<property name="userDao" ref="mysqlImpl"/>
</bean>
</beans>
每个标签中的ID 对应的是实现类的实例化对象,class则是对应的实体类路径。
业务层的标签的property属性里,有两个属性:name和ref. 前者指的是实现类的接口。 后者指定的是指向的需要实现的类。
测试:
要使用Spring容器,就要先拿到ApplicationContext对象:
public class MyTest {
public static void main(String[] args) {
//获取ApplicationContext对象,拿到Spring容器
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("Beans.xml");
UserServiceImpl userService = (UserServiceImpl)applicationContext.getBean("userService");
userService.getUser();
}
}
拿到context对象后,需要什么,就直接从里面get什么。
这里拿到容器里面的userServiceImpl对象,执行里面的getUser()方法,查询出结果