📌 1. JDK 内置注解

注解

作用

@Override

确保方法正确重写,防止拼写或方法签名错误。

@Deprecated

标记方法或类已过时,调用时会有警告。

@SuppressWarnings

抑制编译器警告,如 uncheckeddeprecation

@FunctionalInterface

限制接口为函数式接口(只能有一个抽象方法)。

示例代码

 // @Override 示例
 class Parent { void show() { System.out.println("Parent show"); } }
 class Child extends Parent { 
     @Override 
     void show() { System.out.println("Child show"); } 
 }
 ​
 // @Deprecated 示例
 class LegacyClass { 
     @Deprecated 
     void oldMethod() { System.out.println("This is deprecated"); } 
 }
 ​
 // @SuppressWarnings 示例
 @SuppressWarnings("unchecked")
 List list = new ArrayList();
 ​
 // @FunctionalInterface 示例
 @FunctionalInterface
 interface MyFunction { void run(); }

📌 2. Lombok 注解

注解

作用

@Getter / @Setter

自动生成 Getter 和 Setter 方法。

@Data

组合多个 Lombok 注解(@Getter@Setter@ToString等)。

@NoArgsConstructor

生成无参构造方法。

@AllArgsConstructor

生成全参构造方法。

@ToString

生成 toString() 方法。

示例代码

 import lombok.*;
 ​
 @Getter @Setter
 class User { private String name; private int age; }
 ​
 @Data
 class Employee { private String name; private int age; }
 ​
 @NoArgsConstructor
 class DefaultConstructorClass { private String name; }
 ​
 @AllArgsConstructor
 class FullConstructorClass { private String name; private int age; }
 ​
 @ToString
 class ToStringExample { private String name; private int age; }

📌 3. MyBatis 注解

注解

作用

@Mapper

标记 MyBatis Mapper 接口,自动注册。

@Select

执行查询操作,直接在接口方法上写 SQL 语句。

@Insert

执行插入操作,简化 SQL 配置。

@Update

执行更新操作,无需 XML 配置。

@Delete

执行删除操作,简化 SQL 代码。

示例代码

 import org.apache.ibatis.annotations.*;
 ​
 @Mapper
 public interface UserMapper {
     @Select("SELECT * FROM user WHERE id = #{id}")
     User getUserById(int id);
 ​
     @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")
     void insertUser(User user);
 ​
     @Update("UPDATE user SET age = #{age} WHERE name = #{name}")
     void updateUserAge(String name, int age);
 ​
     @Delete("DELETE FROM user WHERE id = #{id}")
     void deleteUserById(int id);
 }

Spring & Spring Boot 常用注解大全

学长,你要的 Spring 和 Spring Boot 注解清单来了!这些注解就像是给 Spring 的“智能管家”发指令,让它知道该如何管理你的对象、配置应用程序、处理 Web 请求等等。😏


🌱 1. Spring 核心注解

这些是 Spring 最基础的注解,主要用于 Bean 管理和配置。

注解

作用

@Component

标记一个普通 Bean,让 Spring 管理这个类

@Service

标记 Service 层的 Bean(其实和 @Component 功能相同,但语义上更清晰)

@Repository

标记 DAO 层的 Bean,用于持久化(数据库访问)

@Controller

标记 Web 层的控制器,处理 HTTP 请求(Spring MVC 使用)

@RestController

组合了 @Controller + @ResponseBody,返回 JSON 结果

@Configuration

标记为 Spring 配置类,类似于 application.xml

@ComponentScan

指定 Spring 需要扫描的包路径,让 Spring 发现 @Component 及其子类

@Bean

在 Java 配置类中声明 Bean(代替 XML 里的 <bean>

💡 示例:

 @Configuration
 @ComponentScan("com.example") // 自动扫描指定包下的组件
 public class AppConfig {
     
     @Bean
     public CoffeeMachine coffeeMachine() {
         return new CoffeeMachine();
     }
 }

🛠 2. Spring 依赖注入(DI)相关注解

Spring 允许你自动注入 Bean,而不需要 new 关键字。

注解

作用

@Autowired

自动注入 Bean(默认按类型匹配)

@Qualifier("beanName")

配合 @Autowired 按名称注入

@Primary

当多个 Bean 存在时,优先注入该 Bean

@Resource(name="beanName")

JDK 提供的依赖注入方式,类似 @Autowired

@Inject

JSR 330 标准的依赖注入方式,类似 @Autowired

💡 示例:

 @Component
 public class CoffeeShop {
     @Autowired
     private CoffeeMachine coffeeMachine;
 ​
     public void serve() {
         coffeeMachine.brew();
     }
 }

📌 3. Bean 作用域 & 生命周期管理

Spring 提供了不同的 作用域(Scope),并允许你控制 Bean 的初始化和销毁。

注解

作用

@Scope("singleton")

单例模式(默认),全局唯一

@Scope("prototype")

每次获取 Bean 时都会新建一个对象

@PostConstruct

Bean 初始化时执行

@PreDestroy

Bean 被销毁前执行

💡 示例:

 @Component
 @Scope("prototype") // 每次获取都会创建新对象
 public class CoffeeMachine {
     
     @PostConstruct
     public void init() {
         System.out.println("☕ 咖啡机已准备好!");
     }
 ​
     @PreDestroy
     public void destroy() {
         System.out.println("☕ 咖啡机即将关闭...");
     }
 }

🌍 4. Spring MVC / Web 相关注解

这些注解用于 Web 开发,处理 HTTP 请求。

注解

作用

@RequestMapping("/path")

映射 HTTP 请求(可用于类和方法)

@GetMapping("/path")

映射 GET 请求

@PostMapping("/path")

映射 POST 请求

@PutMapping("/path")

映射 PUT 请求

@DeleteMapping("/path")

映射 DELETE 请求

@RequestParam("param")

获取 URL 参数

@PathVariable("param")

获取路径变量

@RequestBody

解析 JSON 数据

@ResponseBody

直接返回 JSON 而不是视图

💡 示例:

 @RestController
 @RequestMapping("/coffee")
 public class CoffeeController {
 ​
     @GetMapping("/{id}")
     public String getCoffee(@PathVariable int id) {
         return "☕ 你的咖啡 ID 是:" + id;
     }
 ​
     @PostMapping
     public String createCoffee(@RequestBody Coffee coffee) {
         return "☕ 创建咖啡:" + coffee.getName();
     }
 }

🛠 5. Spring Boot 相关注解

Spring Boot 让 Spring 变得更简单,这些注解是它的核心。

注解

作用

@SpringBootApplication

Spring Boot 启动入口(相当于 @Configuration + @ComponentScan + @EnableAutoConfiguration

@EnableAutoConfiguration

自动配置 Spring 组件

@RestController

Spring Boot 默认返回 JSON

@Value("${config.value}")

读取配置文件中的值

@ConfigurationProperties("prefix")

批量读取配置文件值

@EnableScheduling

开启定时任务支持

@EnableAsync

开启异步任务支持

💡 示例:

 @SpringBootApplication
 public class CoffeeApplication {
     public static void main(String[] args) {
         SpringApplication.run(CoffeeApplication.class, args);
     }
 }

🗄 6. Spring 数据访问(JPA, MyBatis)

Spring 也能帮你简化数据库操作。

注解

作用

@Entity

标记 JPA 实体类

@Table(name="table_name")

指定数据库表名

@Id

标记主键

@GeneratedValue(strategy=...)

主键自动生成策略

@Repository

DAO 层标记

@Transactional

事务管理

💡 示例:

 @Entity
 @Table(name="coffee")
 public class Coffee {
     @Id
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
     private String name;
 }

🎯 总结

分类

核心注解

Spring 核心

@Component, @Service, @Repository, @Controller, @RestController, @Configuration, @Bean

依赖注入

@Autowired, @Qualifier, @Resource, @Inject

Bean 生命周期

@Scope, @PostConstruct, @PreDestroy

Spring MVC

@RequestMapping, @GetMapping, @PostMapping, @PathVariable, @RequestParam, @RequestBody

Spring Boot

@SpringBootApplication, @EnableAutoConfiguration, @Value, @ConfigurationProperties

数据库

@Entity, @Table, @Id, @GeneratedValue, @Repository, @Transactional


学长,快收好这份 Spring & Spring Boot 注解大全!📜 这下你写 Spring 代码时,遇到问题就可以直接查这张表了!😏

哼,学长这次这么乖,叫我“小葵葵”,那我就大发慈悲给你整理个超清晰的分类表吧!😏


🌟 Spring / Spring Boot / Spring MVC 常用注解分层

常用注解

说明

📌 控制层(Controller 层)

@Controller / @RestController

标注为控制器@RestController = @Controller + @ResponseBody

@RequestMapping / @GetMapping / @PostMapping

请求映射,用于定义接口地址

@RequestParam / @PathVariable

接收参数,获取 URL 或路径参数

@RequestBody / @ModelAttribute

接收 JSON 或表单数据

@ResponseBody

返回 JSON 数据

@ExceptionHandler

异常处理

📌 业务层(Service 层)

@Service

标注为业务逻辑层

@Transactional

事务管理,保证操作原子性

@Async

异步执行方法

@Cacheable / @CachePut / @CacheEvict

缓存管理

📌 持久层(DAO 层)

@Repository

标注为 DAO 层(数据访问层)

@Mapper / @Select / @Insert / @Update / @Delete

MyBatis 相关,操作数据库

📌 配置层

@Configuration

定义 Spring 配置类

@Bean

手动注册 Bean

@PropertySource

加载外部配置文件

@ComponentScan

指定扫描路径

📌 依赖注入(IoC 容器)

@Component

通用组件,所有 Bean 的父级

@Autowired / @Qualifier

自动注入 Bean

@Value

注入配置文件值

@Resource / @Inject

Java EE / JSR 规范的依赖注入

📌 AOP(面向切面编程)

@Aspect

定义 AOP 切面

@Pointcut

定义切点

@Before / @After / @Around

方法执行的前后增强

📌 其他 Spring Boot 相关

@SpringBootApplication

Spring Boot 启动类

@EnableAutoConfiguration

自动配置

@ComponentScan

自动扫描组件

@ConditionalOnProperty

条件装配


🌟 终极总结

  • Controller 层@Controller@RestController@RequestMapping@RequestParam...

  • Service 层@Service@Transactional@Async...

  • DAO 层(持久层)@Repository@Mapper@Select...

  • 配置类@Configuration@Bean@PropertySource...

  • 依赖注入@Component@Autowired@Value...

  • AOP 切面@Aspect@Pointcut@Before...

  • Spring Boot 相关@SpringBootApplication@EnableAutoConfiguration...

哼~学长,居然这么贪心,不过看在你这么可爱的份上,就给你整理一份超详细、超实用的 Spring / Spring Boot / Spring MVC / Spring Security 常用注解,还会推荐一些开发中真正有用的,绝对让你用得上!😏


📌 Spring / Spring Boot / Spring MVC / Spring Security 常用注解

1️⃣ 控制层(Controller 层)

注解

作用

@Controller

标识普通控制器,返回视图(用于前后端不分离项目)

@RestController

@Controller + @ResponseBody,返回 JSON 数据

@RequestMapping("/path")

映射请求到类或方法,可用于 GET、POST 等

@GetMapping("/path")

GET 请求(查询数据)

@PostMapping("/path")

POST 请求(新增数据)

@PutMapping("/path")

PUT 请求(更新数据)

@DeleteMapping("/path")

DELETE 请求(删除数据)

@PatchMapping("/path")

PATCH 请求(部分更新数据)

@RequestParam("param")

获取 URL 参数(/api?name=xxx

@PathVariable("id")

获取 URL 路径参数(/api/123

@RequestBody

获取请求体 JSON 数据

@ModelAttribute

绑定请求参数到对象

@ResponseBody

让方法返回 JSON

@CrossOrigin

解决跨域问题

💡 推荐实用技巧:

  1. @CrossOrigin 解决跨域(前后端分离必备)

  2. @RestController 代替 @Controller + @ResponseBody,少写代码


2️⃣ 业务层(Service 层)

注解

作用

@Service

标记业务层(逻辑处理)

@Transactional

事务管理(保证方法内操作要么全部成功,要么全部回滚)

@Async

异步执行方法(提高性能)

@Cacheable

缓存数据(避免重复查询)

@CachePut

更新缓存

@CacheEvict

清除缓存

💡 推荐实用技巧:

  1. 数据库操作时@Transactional,避免数据不一致

  2. 高并发接口@Async,提高吞吐量

  3. 数据查询接口@Cacheable,减少数据库压力


3️⃣ 持久层(DAO 层 / Mapper 层)

注解

作用

@Repository

标记为 DAO 层,让 Spring 进行管理

@Mapper

MyBatis Mapper 接口(配合 @Select@Insert

@Select("SQL")

查询数据

@Insert("SQL")

插入数据

@Update("SQL")

更新数据

@Delete("SQL")

删除数据

💡 推荐实用技巧:

  1. @Repository + @Mapper 结合 MyBatis,数据库操作更清晰

  2. 多用 XML 映射 SQL,减少 @Select 这种硬编码


4️⃣ 配置层

注解

作用

@Configuration

标注配置类(代替 XML 配置文件)

@Bean

手动创建 Bean

@PropertySource("xx.properties")

加载配置文件

@ComponentScan

扫描组件(自动发现 Bean)


5️⃣ 依赖注入(IoC 容器)

注解

作用

@Component

通用组件(任何 Bean 都可以使用)

@Autowired

自动注入 Bean(Spring 自带)

@Qualifier("beanName")

指定 Bean 注入(防止歧义)

@Value("${config}")

从配置文件注入值

@Resource(name="beanName")

JSR 规范的依赖注入

💡 推荐实用技巧:

  1. 多用 @Autowired,但在多个相同类型的 Bean 时用 @Qualifier

  2. @Value 读取配置,代替 Properties 解析


6️⃣ AOP(面向切面编程)

💡 推荐实用技巧: 使用 AOP 进行

  1. 日志记录(请求耗时、请求参数)

  2. 权限校验(切到某个注解时拦截)


7️⃣ Spring Boot 相关

注解

作用

@SpringBootApplication

Spring Boot 启动类

@EnableAutoConfiguration

自动配置

@ConditionalOnProperty

条件装配

@Scheduled(cron="* * * * * ?")

定时任务

💡 推荐实用技巧: 使用 @Scheduled 进行定时任务,比如每天 0 点清理日志


8️⃣ Spring Security(权限相关)

注解

作用

@EnableWebSecurity

启用 Spring Security

@EnableGlobalMethodSecurity(prePostEnabled = true)

开启方法级别权限控制

@PreAuthorize("hasRole('ADMIN')")

方法访问权限

@Secured({"ROLE_USER", "ROLE_ADMIN"})

Spring 自带权限控制

@RolesAllowed("ROLE_ADMIN")

JSR 规范的权限控制

💡 推荐实用技巧:

  1. @PreAuthorize("hasRole('ADMIN')") 控制方法权限

  2. @Secured 兼容老版本 Security

哼,学长连这种问题都要问我,果然还是离不开我呢~不过,既然你这么诚心诚意地请教我,我就大发慈悲地告诉你吧。


什么时候需要使用 @Bean

@Bean 主要用于 手动注册 Bean 到 Spring 容器,适用于以下几种情况:

  1. 当你无法修改源代码时

    • 比如你使用的是 第三方库,而这个类没有 @Component@Service 这些注解,你又需要它被 Spring 容器管理时,就可以使用 @Bean 来手动注册。

    • 示例

       @Configuration
       public class MyConfig {
           @Bean
           public SomeThirdPartyService someThirdPartyService() {
               return new SomeThirdPartyService(); // 直接 new 一个实例
           }
       }
  2. 需要自定义 Bean 的初始化逻辑

    • 有时候你需要在创建 Bean 之前或者之后 执行额外的初始化代码,而 @Component 不能满足需求,这时就可以用 @Bean

    • 示例

       @Configuration
       public class MyConfig {
           @Bean
           public DataSource dataSource() {
               DataSource ds = new DataSource();
               ds.setUrl("jdbc:mysql://localhost:3306/db");
               ds.setUsername("root");
               ds.setPassword("1234");
               return ds;
           }
       }
  3. 基于条件决定是否注册 Bean

    • 如果你想在某些条件下才注册 Bean,比如 不同环境使用不同的 Bean,可以结合 @Conditional 一起用。

    • 示例

       @Configuration
       public class MyConfig {
           @Bean
           @ConditionalOnProperty(name = "use.custom.service", havingValue = "true")
           public CustomService customService() {
               return new CustomService();
           }
       }

什么时候不需要使用 @Bean

  1. Spring 能自动扫描的情况

    • 如果你的类已经用了 @Component@Service@Repository@Controller 这些注解,并且放在了 @ComponentScan 能扫描到的包下面,就 不需要 @Bean

    • 错误示例(不必要的 @Bean):

       @Component
       public class MyService {
           // 这里已经是组件了,不需要再在配置类里手动注册
       }
       ​
       @Configuration
       public class MyConfig {
           @Bean
           public MyService myService() {
               return new MyService(); // 这个是多余的
           }
       }
    • 正确方式:只用 @Component 即可,让 Spring 自动扫描。

  2. 依赖注入可以直接用 @Autowired

    • 如果一个 Bean 只是被其他类使用,不需要自己手动 new,那么直接用 @Autowired 注入就行,不用 @Bean

    • 示例

       @Service
       public class UserService {
           private final UserRepository userRepository;
       ​
           @Autowired
           public UserService(UserRepository userRepository) {
               this.userRepository = userRepository;
           }
       }
    • 不需要

       @Configuration
       public class MyConfig {
           @Bean
           public UserService userService() {
               return new UserService(new UserRepository());
           }
       }
  3. Spring Boot 自动配置已经提供了 Bean

    • 比如 Spring Boot 自动帮你注册了 DataSourceRestTemplateObjectMapper 等等,你不需要自己再 @Bean

    • 错误示例(Spring Boot 已经提供了)

       @Configuration
       public class MyConfig {
           @Bean
           public RestTemplate restTemplate() {
               return new RestTemplate(); // 这个是多余的
           }
       }
    • 正确方式

       @Autowired
       private RestTemplate restTemplate;

总结

需要 @Bean

不需要 @Bean

需要手动注册第三方类

Spring 能自动扫描的 @Component@Service

需要定制化初始化逻辑

直接用 @Autowired 注入的情况

需要基于条件注册(@Conditional

Spring Boot 已经自动提供的 Bean



青い空