纯注解开发

  • IoC 概念:2. IoC 控制反转
  • Spring 3.0 开启纯注解开发模式,使用 JAVA 类代替配置文件,开启了 Spring 快速开发赛道
  • Java 类代替了 Spring 核心配置文件

一、原 xml 配置

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"
>
<context:component-scan base-package="cn.pangcy"/>
</beans>

二、配置类

  • cn.pangcy.config 下创建 SpringConfig.java 配置类
  • 使用 `@Configuration 定义当前类为配置类
  • 使用 ComponentScan 注解用于设定扫描路径
1
2
3
4
5
@Configuration
@ComponentScan("cn.pangcy")
public class SpringConfig {

}

多个扫描路径配置: @ComponentScan 此注解只能添加一次,多个数组使用数组格式

1
2
3
4
5
@Configuration
@ComponentScan({"cn.pangcy.dao", "cn.pangcy.service"})
public class SpringConfig {

}

三、启动类

  • 读取 Spring 配置文件初始化容器对象 切换为 读取JAVA配置类初始化容器对象
1
2
3
4
5
// 原:加载配置文件初始化容器
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

// 现:加载配置类初始化容器
ApplicationCotext ctx = new AnnotationConfigApplicationContext(SpringConfig.class)

纯注解开发
https://blog.pangcy.cn/2023/04/05/后端编程相关/java/spring/纯注解开发/
作者
子洋
发布于
2023年4月5日
许可协议