SpringBootApplication
主程序入口位置
Primary 首选 Bean
当多个 Bean 符合注入条件时,优先选择 @Primary
标注的 Bean。
@Component
@Primary
public class FirstService implements MyService {
// 默认优先注入该实现
}
Qualifier (指定Bean名称)
当有多个相同类型的 Bean 时,指定要注入的 Bean,避免歧义。详细说明请看:
报错:No qualifying bean of type ‘xx‘ available。SpringBoot注释@Qualifier的作用-CSDN博客
Autowired
自动导入bean
Service
标记业务层组件
Component
是spring最基础的组件注解,泛指所有Spring 管理的 Bean。适用于 所有类型的组件(Service、DAO、工具类等)。
可以设定bean的名称:
@Component("beanA")
public class Bean {}
Repository
继承于Component,标记持久层组件,专门用于DAO数据访问层,用于与数据库交互的组件。
- 提供异常转换:Spring 会将 JDBC 异常 转换为 Spring 统一的
DataAccessException
,提高可读性和可维护性。 - 适用于 JPA、JdbcTemplate、Hibernate 等数据访问技术。
示例(使用 @Repository
结合 JPA)
@Repository
public class UserRepository {
@Autowired
private JdbcTemplate jdbcTemplate;
public void saveUser(String name) {
String sql = "INSERT INTO users (name) VALUES (?)";
jdbcTemplate.update(sql, name);
}
}
Mapper
- 标记 MyBatis 的 Mapper 接口,使其被 MyBatis 识别并创建代理对象。
- 不需要手写实现类,只需要定义接口和 SQL 语句。
- 适用于 MyBatis 框架。
示例(使用 @Mapper
结合 MyBatis)
@Mapper
public interface UserMapper {
@Insert("INSERT INTO users (name) VALUES (#{name})")
void saveUser(String name);
}
这里
UserMapper
只是一个接口,Spring 会自动创建实现类并管理它。
控制接口层
Controller
标记控制层SpringMVC层
RestController
包含了Controller和ResponseBody两个注解,适用于REST API,也称RESTful API控制器,直接返回JSON数据,而非视图模版。
@RestController
public class UserRestController {
@GetMapping("/user")
public String getUser() {
return "返回 JSON 数据";
}
}
ResponseBody
将接口中返回的数据写到返回响应体中
RequestMapping
定义url,接口的访问地址,可以通过value和method指定请求的url和方法。getMapping和postMapping则直接规定了请求的方法。
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(){
}
PathVariable
接受占位符方式传参,例如url中注释的/getName/{name},则接口函数中应该传参@PathVariable("name") String name,函数中便可直接使用name参数。
@GetMapping("/test/${name}")
public String helloWorld(@PathVariable("name") String name){
}
RequestParam
接受url中的参数,例如:
http://localhost/helloworld?name=a&age=15
则接口函数应该为:
@
public String test(@RequestParam String name,@RequestParam Interge age)
RequestBody
接受请求体里面的参数,一般用于接受json字符串转化为实体对象
对面传来请求体json字符串:
{
name: 'Jack',
age: 17
}
public class User{
private String name;
privte Interge age;
public getName(){
return name;
}
}
public String test(@RequestBody User user){
return user.getName();
}
Bean生命周期控制
使用@Bean(initMethod, destroyMethod)
控制
对应xml的bean定义,手动创建Bean,而不是用 @Component
自动扫描。可用于创建 第三方库 Bean(无法加 @Component
的类)。支持 initMethod
和 destroyMethod
,控制生命周期。
Spring Bean 的生命周期通常经历以下 5 个阶段:
1️⃣ 实例化(Constructor)
2️⃣ 依赖注入(Dependency Injection)
3️⃣ 初始化(Initialization)
- 例如:
@PostConstruct
、InitializingBean#afterPropertiesSet()
4️⃣ Bean 正常使用(In Use)
5️⃣ 销毁(Destruction)
- 例如:
@PreDestroy
、DisposableBean#destroy()
实例化 → 依赖注入 → 初始化方法 → Bean 可用 → 销毁方法
@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public MyBean myBean() {
return new MyBean();
}
}
class MyBean {
public void init() {
System.out.println("Bean 初始化:initMethod 方法执行");
}
public void destroy() {
System.out.println("Bean 销毁:destroyMethod 方法执行");
}
}
使用@PostConstruct
和 @PreDestroy
PostConstruct 初始化执行
作用:Spring 完成 依赖注入 后,自动执行 标注的方法。
触发时机:Bean 初始化 之后,使用前执行。
@Component
public class MyBean {
public MyBean() {
System.out.println("1️⃣ 构造方法执行:MyBean 被创建");
}
@PostConstruct
public void init() {
System.out.println("2️⃣ @PostConstruct:MyBean 初始化完成");
}
}
🔹 执行顺序:
✅ 构造方法 → 依赖注入 → ✅ @PostConstruct
方法执行
PreDestroy 销毁时执行
- 作用:Spring 销毁 Bean 之前,执行该方法,释放资源(如关闭数据库连接)。
- 触发时机:Spring 关闭容器 时。
@Component
public class MyBean {
@PreDestroy
public void destroy() {
System.out.println("@PreDestroy:MyBean 即将被销毁");
}
}
使用接口控制
使用接口控制的生命周期执行顺序都在PostConstruct和PreDestroy之后。
初始化:PostConstruct ---> afterPropertiesSet
销毁:PreDestroy ---> destroy
InitializingBean接口初始化
实现 afterPropertiesSet()
方法,在 所有属性注入完成后执行。
@Component
public class MyBean implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Bean 初始化:afterPropertiesSet() 执行");
}
}
执行顺序:
构造方法
→依赖注入
→afterPropertiesSet()
DisposableBean接口销毁
实现 destroy()
方法,在 Spring 销毁 Bean 之前执行。
@Component
public class MyBean implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("Bean 销毁:destroy() 方法执行");
}
}
执行顺序:
destroy()
→ Spring 关闭容器 → Bean 被销毁
Scope控制 Bean 作用域
@Scope("singleton")
(默认): 只创建 一个实例,容器关闭时销毁。不加@Scope时默认就是singleton模式@Scope("prototype")
: 每次getBean()
都会创建 新实例,不会自动销毁(手动释放)。@Scope("
request"):
每个 HTTP 请求 都会创建新的 Bean 实例,每次请求创建,每次请求结束销毁@Scope("
session"):
每个 Session 共享同一个 Bean,Session 结束时销毁
单例与每次创建新实例的区别详细请看:SpringBoot单例与每次创建实例的区别-CSDN博客
@Component
@Scope("prototype") // 每次获取都会创建新的实例
public class PrototypeBean {
@PostConstruct
public void init() {
System.out.println("PrototypeBean 初始化");
}
@PreDestroy
public void destroy() {
System.out.println("PrototypeBean 销毁");
}
}
prototype
作用域下,@PreDestroy
不会执行,因为 Spring 不会管理 prototype Bean 的销毁!
Lazy懒加载Bean
@Component
@Lazy
public class LazyBean {
public LazyBean() {
System.out.println("LazyBean 构造方法执行");
}
}
只有在第一次
getBean()
时才会创建LazyBean
配置注释
Configuration
对应Spring的Beans
Value
读取配置文件的变量,比如yml文件或者properties配置文件,使用方法为:
@Value("${变量名}")
private String name;
ConfigurationProperties
整体读取配置文件的变量,必须指定前缀参数prefix。它将会寻找配置文件中前缀为参数值的配置项。例如:
properties配置文件:
user.userName = "jack"
user.age = 17
userName = "Tom"
Java代码:
@Configuration
@ConfigurationProperties(prefix = "user")
public class UserConfig{
privte String userName;
privte String age;
// getter and setter...
}
则UserConfig类会自动设置属性userName为jack,age为17