一、存储Bean对象
在这篇文章中我介绍了Spring最简单的创建和使用:Spring的创建和使用
其中存储Bean对象是这样的:
1.1 配置扫描路径
想要成功把对象存到Spring中,我们需要配置对象的扫描包路径
这样的话,就只有被配置了的包中的加了注解的类才会被存储到Spring中
这里的注解是什么?下面我们介绍
xml
<?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:content="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 https://www.springframework.org/schema/context/spring-context.xsd">
<content:component-scan base-package="'com.java.Ethan'"></content:component-scan>
</beans>
1.2 添加注解存储Bean对象

1.3 类注解
1.3.1 @Controller(控制器存储)

1.3.2 @Service(服务存储)

1.3.3 @Repository(仓库存储)

1.3.4 @Component(组件存储)

1.3.5 @Configuration(配置存储)

1.4 关于类注解的疑问
1.4.1 为什么要这么多类注解?

1.4.2 类注解之间的关系

1.4.3 Bean默认命名规则
在源码中就有说明:
1.5 方法注解@Bean
方法注解@Bean必须配合类注解才能将对象存储到Spring
1.6 Bean重命名

二、获取Bean对象
获取 bean 对象也叫做对象装配,是把对象取出来放到某个类中,有时候也叫对象注入。
下⾯我们按照实际开发中的模式,将 Service 类 注⼊到 Controller 类中。
2.1 属性注入

注意:
2.2 Setter注入
2.3 构造方法注入
构造方法注入是 Spring 官方从 4.x 之后推荐的注入方式
注意:
只有一个构造方法的时候,可以省略注解@Autowired