IOC&DI
Inversion Of Control控制反转(在运行时基于反射发现和注册的过程)(IOC容器发现组件,类)
发现:运行时让IOC容器发现组件类
1.组件类的包层级不能高于启动类,只能小于等于
2.组件类上需要有IOC注解
注册:发现后就会触发注册,注册就是创建对象放入到IOC容器
Dependency Injection 依赖注入(赋值的过程)
注入:在运行时,从IOC容器找到与指针相匹配的对象赋值给指针的过程、
发现----------》注册------------------》注入
都是在运行时发生
具有IOC功能的注解有哪些?
1.@Controller/@RestController
(1) 用于控制器层类的发现和注册
2.@Service
(1 用于Service层类的发现和注册
3.@Repository(如果用了MyBatis框架就不会用到这个注解)
(1) 用于Dao层类的发现和注册
4.@Component
(1) 用于任意一个普通类的发现和注册
5.@MapperScan() 苞米豆提供,前四是Spring提供
(1) 用于扫描mapper包,在运行时创建接口和实现类,并注册对象到IOC容器
什么控制权?
创建对象的控制权 new 构造方法()
为什么要反转?
高内聚低耦合
耦合=依赖(工程依赖工程,类依赖类)
Component 组件(组成工程的元件,指的是类)
Bean/JavaBean 咖啡豆/组成(指的对象/被IOC容器放学后创建的对象)
IOC的实现方式有3种
发现 - 注入 - 注册
1.基于xml文件实现(已经淘汰)
2.基于注解实现
3.基于配置类实现
启动类就是一个配置类,或者任意一个带有@Configuration注解的类都可以是一个配置类
发现/注册UserController
发现/注册UserServiceImpl
在UserController中注入UserService
在Resource创建xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
</beans>
去掉所有注释
在启动类加注解
第三种方法
AOP
面向切面编程
Aspect Oriented Programming
try.catch() finally() 非业务代码
log.debug("")侵入式代码
使代码更优雅
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.7.2</version>
</dependency>