摘要:本文学习了Spring中控制反转和依赖注入的基本概念和使用方法。
环境
Windows 10 企业版 LTSC 21H2
Java 1.8
Tomcat 8.5.50
Maven 3.6.3
Spring 5.2.25.RELEASE
1 容器
容器是Spring框架的核心组件,负责管理应用程序中的对象的生命周期。Spring提供了BeanFactory和ApplicationContext两种主要的容器实现。
1.1 BeanFactory
基础容器,提供基本的依赖注入支持。
在加载配置文件时不会创建对象,只有在使用的时候才会创建对象。
1.2 ApplicationContext
BeanFactory的扩展,提供更多企业级功能。
ApplicationContext在初始化上下文时就实例化所有的单例对象,主要的实现类:
- ClassPathXmlApplicationContext:从类路径加载XML配置。
- FileSystemXmlApplicationContext:从文件系统加载XML配置。
- AnnotationConfigApplicationContext:基于注解配置。
2 配置方式
在容器中,配置主要有三种方式:
- XML配置:这是Spring最早支持的配置方式。在XML文件中声明对象,并描述它们之间的依赖关系。
- 半注解配置:从2.5版本开始引入了注解驱动的配置。通过扫描类路径下的注解,自动注册对象。
- 全注解配置:从3.0版本开始引入了全注解配置,使用配置类代替配置文件,使用
@Configuration注解和@Bean注解。
3 依赖注入
在容器中,注入对象主要有三种方式:
- 构造器注入:通过构造器注入依赖。这是Spring推荐的方式,特别是必选依赖的情况。
- 方法注入:通过方法注入依赖。这种方式适用于可选依赖,或者需要改变依赖的情况。
- 字段注入:通过在字段上使用注解注入依赖。这种方式非常简洁,但有一些缺点。
4 入门案例
目录结构:
code1 2 3 4 5 6 7 8 9 10 11
| demo-spring/ ├── src/ │ ├── main/ │ │ ├── java/ │ │ │ └── com/example/ │ │ │ ├── bean/ │ │ │ │ └── User.java │ │ │ └── DemoApplication.java │ │ └── resources/ │ │ └── spring.xml └── pom.xml
|
创建pom.xml文件:
pom.xml1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId> <artifactId>demo-spring</artifactId> <version>1.0.0-SNAPSHOT</version>
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.25.RELEASE</version> </dependency> </dependencies> </project>
|
创建实体类:
java1 2 3 4 5
| public class User { private Integer id; private String name; }
|
创建配置文件:
spring.xml1 2 3 4 5 6 7 8
| <?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="user" class="com.example.bean.User"/> </beans>
|
创建启动类:
java1 2 3 4 5 6 7 8 9 10 11 12
| public class DemoApplication { public static void main(String[] args) { ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml"); User user = context.getBean(User.class); System.out.println(user); context.close(); } }
|
执行启动类的main()方法。
条