Java常用注解
一、Java基础注解 ★★★★☆
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Java基础 | @Override |
表示方法重写父类方法 | ★★★★★ | @Override<br>public String toString() { return "示例"; } |
| Java基础 | @Deprecated |
标记类、方法或字段已过时,不推荐使用 | ★★★★☆ | @Deprecated<br>public void oldMethod() {} |
| Java基础 | @SuppressWarnings |
抑制编译器警告 | ★★★☆☆ | @SuppressWarnings("unchecked")<br>List list = new ArrayList(); |
| Java基础 | @SafeVarargs |
抑制泛型可变参数警告(Java 7+) | ★★☆☆☆ | @SafeVarargs<br>public static <T> void print(T... args) {} |
| Java基础 | @FunctionalInterface |
标记函数式接口(Java 8+) | ★★★★☆ | @FunctionalInterface<br>interface Converter<T, R> { R convert(T t); } |
| Java基础 | @Retention |
元注解:定义注解保留策略(SOURCE/CLASS/RUNTIME) | ★★★☆☆ | @Retention(RetentionPolicy.RUNTIME) |
| Java基础 | @Target |
元注解:定义注解使用目标(TYPE/METHOD/FIELD等) | ★★★☆☆ | @Target({ElementType.METHOD, ElementType.TYPE}) |
| Java基础 | @Documented |
元注解:标记注解是否包含在JavaDoc中 | ★★☆☆☆ | @Documented<br>public @interface MyAnnotation {} |
| Java基础 | @Inherited |
元注解:允许子类继承父类的注解 | ★★☆☆☆ | @Inherited<br>public @interface MyAnnotation {} |
| Java基础 | @Repeatable |
元注解:表示注解可以重复使用(Java 8+) | ★★☆☆☆ | @Repeatable(Schedules.class)<br>public @interface Schedule {} |
| Java基础 | @Native |
标记字段是本地代码引用 | ★☆☆☆☆ | @Native<br>public static final int MAX_VALUE = 0x7fffffff; |
二、Spring框架注解 ★★★★★
Spring核心注解
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Spring Core | @Component |
通用组件注解,标记为Spring Bean | ★★★★★ | @Component<br>public class UserService {} |
| Spring Core | @Service |
业务层组件注解 | ★★★★★ | @Service<br>public class UserServiceImpl {} |
| Spring Core | @Repository |
数据访问层组件注解 | ★★★★★ | @Repository<br>public class UserDaoImpl {} |
| Spring Core | @Controller |
Web控制层组件注解 | ★★★★★ | @Controller<br>public class UserController {} |
| Spring Core | @RestController |
组合注解:@Controller + @ResponseBody | ★★★★★ | @RestController<br>public class UserController {} |
| Spring Core | @Configuration |
标记配置类,定义Spring容器配置 | ★★★★★ | @Configuration<br>public class AppConfig {} |
| Spring Core | @Bean |
声明Bean方法,在配置类中使用 | ★★★★★ | @Bean<br>public DataSource dataSource() { return new DataSource(); } |
| Spring Core | @Autowired |
自动注入依赖(按类型) | ★★★★★ | @Autowired<br>private UserService userService; |
| Spring Core | @Qualifier |
按名称注入Bean,解决多个同类型Bean的歧义 | ★★★★☆ | @Autowired<br>@Qualifier("userServiceA")<br>private UserService userService; |
| Spring Core | @Resource |
JSR-250注解,按名称自动注入 | ★★★☆☆ | @Resource(name="userService")<br>private UserService userService; |
| Spring Core | @Value |
注入属性值,支持SpEL表达式 | ★★★★★ | @Value("${app.name}")<br>private String appName; |
| Spring Core | @Scope |
定义Bean作用域(singleton/prototype/request/session等) | ★★★★☆ | @Bean<br>@Scope("prototype")<br>public User user() { return new User(); } |
| Spring Core | @Profile |
环境配置激活,指定哪些环境下生效 | ★★★★☆ | @Configuration<br>@Profile("dev")<br>public class DevConfig {} |
| Spring Core | @Primary |
标记为首选Bean,解决自动装配时的歧义 | ★★★★☆ | @Bean<br>@Primary<br>public DataSource primaryDataSource() { return new DataSource(); } |
| Spring Core | @Lazy |
延迟初始化Bean,直到第一次使用时才创建 | ★★★☆☆ | @Bean<br>@Lazy<br>public HeavyBean heavyBean() { return new HeavyBean(); } |
| Spring Core | @Import |
导入其他配置类 | ★★★★☆ | @Configuration<br>@Import({ConfigA.class, ConfigB.class}) |
| Spring Core | @ImportResource |
导入XML配置文件 | ★★☆☆☆ | @Configuration<br>@ImportResource("classpath:applicationContext.xml") |
| Spring Core | @PropertySource |
加载属性文件 | ★★★★☆ | @Configuration<br>@PropertySource("classpath:application.properties") |
| Spring Core | @PropertySources |
加载多个属性文件 | ★★★☆☆ | @PropertySources({<br>@PropertySource("classpath:app.properties"),<br>@PropertySource("classpath:db.properties")<br>}) |
| Spring Core | @DependsOn |
定义Bean之间的依赖顺序 | ★★☆☆☆ | @Bean<br>@DependsOn("dataSource")<br>public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(); } |
| Spring Core | @Lookup |
方法注入,每次调用返回新的实例 | ★☆☆☆☆ | @Lookup<br>public abstract PrototypeBean getPrototypeBean(); |
Spring MVC注解
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Spring MVC | @RequestMapping |
映射HTTP请求到处理方法 | ★★★★★ | @RequestMapping(value="/user", method=RequestMethod.GET) |
| Spring MVC | @GetMapping |
GET请求映射(Spring 4.3+) | ★★★★★ | @GetMapping("/{id}")<br>public User getById(@PathVariable Long id) {} |
| Spring MVC | @PostMapping |
POST请求映射(Spring 4.3+) | ★★★★★ | @PostMapping("/create")<br>public Result create(@RequestBody User user) {} |
| Spring MVC | @PutMapping |
PUT请求映射(Spring 4.3+) | ★★★★★ | @PutMapping("/update/{id}")<br>public Result update(@PathVariable Long id, @RequestBody User user) {} |
| Spring MVC | @DeleteMapping |
DELETE请求映射(Spring 4.3+) | ★★★★★ | @DeleteMapping("/{id}")<br>public Result delete(@PathVariable Long id) {} |
| Spring MVC | @PatchMapping |
PATCH请求映射(Spring 4.3+) | ★★★☆☆ | @PatchMapping("/partial/{id}")<br>public Result partialUpdate(@PathVariable Long id) {} |
| Spring MVC | @PathVariable |
获取URL路径参数 | ★★★★★ | @GetMapping("/{id}")<br>public User getById(@PathVariable("id") Long userId) {} |
| Spring MVC | @RequestParam |
获取请求参数 | ★★★★★ | @GetMapping("/list")<br>public List<User> list(@RequestParam(defaultValue="1") Integer page) {} |
| Spring MVC | @RequestBody |
获取请求体JSON/XML数据 | ★★★★★ | @PostMapping<br>public Result save(@RequestBody User user) {} |
| Spring MVC | @ResponseBody |
返回JSON/XML数据 | ★★★★★ | @ResponseBody<br>@GetMapping("/{id}")<br>public User getById(@PathVariable Long id) {} |
| Spring MVC | @RequestHeader |
获取请求头信息 | ★★★☆☆ | @RequestHeader("User-Agent") String userAgent |
| Spring MVC | @CookieValue |
获取Cookie值 | ★★★☆☆ | @CookieValue("JSESSIONID") String sessionId |
| Spring MVC | @ModelAttribute |
绑定参数到模型,可用于方法或参数 | ★★★☆☆ | @ModelAttribute<br>public void addAttributes(Model model) { model.addAttribute("msg", "hello"); } |
| Spring MVC | @SessionAttributes |
模型属性存储到Session | ★★☆☆☆ | @SessionAttributes("user")<br>public class UserController {} |
| Spring MVC | @SessionAttribute |
访问Session属性 | ★★☆☆☆ | @SessionAttribute("user") User user |
| Spring MVC | @RequestPart |
处理multipart/form-data请求的部分内容 | ★★★☆☆ | @RequestPart("file") MultipartFile file |
| Spring MVC | @ResponseStatus |
设置HTTP响应状态码 | ★★★★☆ | @ResponseStatus(HttpStatus.NOT_FOUND)<br>public class ResourceNotFoundException extends RuntimeException {} |
| Spring MVC | @CrossOrigin |
跨域请求支持 | ★★★★★ | @CrossOrigin(origins = "http://example.com", maxAge = 3600) |
| Spring MVC | @ControllerAdvice |
全局控制器增强,统一异常处理等 | ★★★★★ | @ControllerAdvice<br>public class GlobalExceptionHandler {} |
| Spring MVC | @ExceptionHandler |
异常处理方法 | ★★★★★ | @ExceptionHandler(Exception.class)<br>public Result handleException(Exception e) {} |
| Spring MVC | @InitBinder |
数据绑定初始化 | ★★☆☆☆ | @InitBinder<br>public void initBinder(WebDataBinder binder) { binder.setDisallowedFields("id"); } |
| Spring MVC | @MatrixVariable |
获取URL矩阵变量 | ★☆☆☆☆ | @GetMapping("/users/{id}")<br>public User get(@PathVariable Long id, @MatrixVariable Map<String, String> matrixVars) {} |
| Spring MVC | @RequestAttribute |
访问请求属性 | ★★☆☆☆ | @RequestAttribute("requestId") String requestId |
| Spring MVC | @RestControllerAdvice |
@ControllerAdvice + @ResponseBody | ★★★★★ | @RestControllerAdvice<br>public class GlobalExceptionHandler {} |
Spring Boot注解
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Spring Boot | @SpringBootApplication |
启动类注解(组合@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan) | ★★★★★ | @SpringBootApplication<br>public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } |
| Spring Boot | @EnableAutoConfiguration |
启用自动配置 | ★★★★★ | @EnableAutoConfiguration<br>public class AppConfig {} |
| Spring Boot | @SpringBootConfiguration |
Spring Boot配置类 | ★★★☆☆ | @SpringBootConfiguration<br>public class MyConfig {} |
| Spring Boot | @ConfigurationProperties |
绑定配置属性 | ★★★★★ | @ConfigurationProperties(prefix="app")<br>public class AppProperties { private String name; } |
| Spring Boot | @EnableConfigurationProperties |
启用配置属性绑定 | ★★★★☆ | @EnableConfigurationProperties(AppProperties.class) |
| Spring Boot | @ConditionalOnClass |
条件注解:类存在时生效 | ★★★★☆ | @ConditionalOnClass(DataSource.class)<br>@Bean<br>public DataSource dataSource() {} |
| Spring Boot | @ConditionalOnMissingBean |
条件注解:不存在Bean时生效 | ★★★★☆ | @ConditionalOnMissingBean(DataSource.class) |
| Spring Boot | @ConditionalOnProperty |
条件注解:属性条件满足时生效 | ★★★★☆ | @ConditionalOnProperty(name="app.feature.enabled", havingValue="true") |
| Spring Boot | @ConditionalOnWebApplication |
条件注解:Web应用时生效 | ★★★☆☆ | @ConditionalOnWebApplication |
| Spring Boot | @ConditionalOnExpression |
条件注解:SpEL表达式为true时生效 | ★★★☆☆ | @ConditionalOnExpression("${app.feature.enabled:true}") |
| Spring Boot | @ConditionalOnJava |
条件注解:Java版本满足时生效 | ★★☆☆☆ | @ConditionalOnJava(JavaVersion.EIGHT) |
| Spring Boot | @ConditionalOnResource |
条件注解:资源存在时生效 | ★★☆☆☆ | @ConditionalOnResource(resources="classpath:config.properties") |
| Spring Boot | @ConditionalOnMissingClass |
条件注解:类不存在时生效 | ★★★☆☆ | @ConditionalOnMissingClass("com.example.OldClass") |
| Spring Boot | @ConditionalOnBean |
条件注解:Bean存在时生效 | ★★★★☆ | @ConditionalOnBean(DataSource.class) |
| Spring Boot | @EnableScheduling |
启用定时任务 | ★★★★☆ | @EnableScheduling |
| Spring Boot | @EnableAsync |
启用异步支持 | ★★★★☆ | @EnableAsync |
| Spring Boot | @EnableCaching |
启用缓存支持 | ★★★★☆ | @EnableCaching |
| Spring Boot | @EnableDiscoveryClient |
启用服务发现客户端(如Eureka) | ★★★★☆ | @EnableDiscoveryClient |
| Spring Boot | @EnableFeignClients |
启用Feign客户端 | ★★★★☆ | @EnableFeignClients |
| Spring Boot | @EnableCircuitBreaker |
启用断路器(Hystrix) | ★★★☆☆ | @EnableCircuitBreaker |
| Spring Boot | @EnableHystrix |
启用Hystrix | ★★★☆☆ | @EnableHystrix |
| Spring Boot | @EnableHystrixDashboard |
启用Hystrix仪表盘 | ★★☆☆☆ | @EnableHystrixDashboard |
| Spring Boot | @EnableZuulProxy |
启用Zuul代理 | ★★☆☆☆ | @EnableZuulProxy |
| Spring Boot | @EnableConfigServer |
启用配置服务器 | ★★☆☆☆ | @EnableConfigServer |
| Spring Boot | @EnableAdminServer |
启用Spring Boot Admin服务器 | ★★☆☆☆ | @EnableAdminServer |
| Spring Boot | @EnableEurekaServer |
启用Eureka服务器 | ★★☆☆☆ | @EnableEurekaServer |
| Spring Boot | @EnableAspectJAutoProxy |
启用AspectJ自动代理 | ★★★☆☆ | @EnableAspectJAutoProxy |
Spring事务注解
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Spring事务 | @Transactional |
声明式事务管理 | ★★★★★ | @Transactional(rollbackFor=Exception.class)<br>public void updateUser(User user) { userDao.update(user); } |
| Spring事务 | @EnableTransactionManagement |
启用注解驱动的事务管理 | ★★★★★ | @Configuration<br>@EnableTransactionManagement<br>public class TxConfig {} |
| Spring事务 | @TransactionalEventListener |
事务事件监听器 | ★★★☆☆ | @TransactionalEventListener(phase=TransactionPhase.AFTER_COMMIT)<br>public void handleEvent(UserCreatedEvent event) {} |
三、JPA/Hibernate注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| JPA | @Entity |
标记为JPA实体类 | ★★★★★ | @Entity<br>public class User { ... } |
| JPA | @Table |
指定数据库表名 | ★★★★★ | @Entity<br>@Table(name="t_user", schema="public", indexes={@Index(columnList="name")})<br>public class User { ... } |
| JPA | @Id |
标记主键字段 | ★★★★★ | @Id<br>private Long id; |
| JPA | @GeneratedValue |
主键生成策略 | ★★★★★ | @Id<br>@GeneratedValue(strategy=GenerationType.IDENTITY)<br>private Long id; |
| JPA | @Column |
映射数据库列 | ★★★★★ | @Column(name="user_name", length=50, nullable=false, unique=true)<br>private String username; |
| JPA | @OneToMany |
一对多关系映射 | ★★★★★ | @OneToMany(mappedBy="user", cascade=CascadeType.ALL, orphanRemoval=true)<br>private List<Order> orders = new ArrayList<>(); |
| JPA | @ManyToOne |
多对一关系映射 | ★★★★★ | @ManyToOne(fetch=FetchType.LAZY)<br>@JoinColumn(name="user_id")<br>private User user; |
| JPA | @ManyToMany |
多对多关系映射 | ★★★★☆ | @ManyToMany<br>@JoinTable(name="user_role", <br>joinColumns=@JoinColumn(name="user_id"), <br>inverseJoinColumns=@JoinColumn(name="role_id"))<br>private List<Role> roles; |
| JPA | @OneToOne |
一对一关系映射 | ★★★★☆ | @OneToOne(cascade=CascadeType.ALL)<br>@JoinColumn(name="detail_id")<br>private UserDetail detail; |
| JPA | @JoinColumn |
定义外键列 | ★★★★★ | @JoinColumn(name="department_id", referencedColumnName="dept_id")<br>private Department department; |
| JPA | @Transient |
标记非持久化字段 | ★★★★☆ | @Transient<br>private String tempData; |
| JPA | @Temporal |
日期时间类型映射 | ★★★★☆ | @Temporal(TemporalType.TIMESTAMP)<br>private Date createTime; |
| JPA | @Enumerated |
枚举类型映射 | ★★★★☆ | @Enumerated(EnumType.STRING)<br>private UserStatus status; |
| JPA | @Lob |
大对象字段映射 | ★★★☆☆ | @Lob<br>private String content; // CLOB<br>@Lob<br>private byte[] image; // BLOB |
| JPA | @Embedded |
嵌入对象(值对象) | ★★★☆☆ | @Embedded<br>private Address address; |
| JPA | @Embeddable |
定义可嵌入类 | ★★★☆☆ | @Embeddable<br>public class Address { ... } |
| JPA | @AttributeOverride |
覆盖嵌入对象的属性映射 | ★★☆☆☆ | @AttributeOverride(name="street", column=@Column(name="home_street")) |
| JPA | @SequenceGenerator |
定义序列生成器(Oracle等) | ★★★☆☆ | @SequenceGenerator(name="seq_user", sequenceName="SEQ_USER", allocationSize=1) |
| JPA | @TableGenerator |
定义表生成器 | ★☆☆☆☆ | @TableGenerator(name="table_gen", table="ID_GEN", pkColumnName="GEN_KEY", valueColumnName="GEN_VALUE") |
| JPA | @NamedQuery |
定义命名查询 | ★★★☆☆ | @NamedQuery(name="User.findByName", query="SELECT u FROM User u WHERE u.name = :name") |
| JPA | @NamedNativeQuery |
定义原生命名查询 | ★★★☆☆ | @NamedNativeQuery(name="User.findByNameNative", query="SELECT * FROM user WHERE name = ?", resultClass=User.class) |
| JPA | @SqlResultSetMapping |
定义SQL结果集映射 | ★★☆☆☆ | @SqlResultSetMapping(name="UserMapping", entities=@EntityResult(entityClass=User.class)) |
| JPA | @EntityListeners |
实体监听器 | ★★★☆☆ | @EntityListeners(AuditingEntityListener.class) |
| JPA | @CreatedDate |
自动设置创建日期(Spring Data JPA) | ★★★★★ | @CreatedDate<br>private LocalDateTime createTime; |
| JPA | @LastModifiedDate |
自动设置最后修改日期(Spring Data JPA) | ★★★★★ | @LastModifiedDate<br>private LocalDateTime updateTime; |
| JPA | @CreatedBy |
自动设置创建者(Spring Data JPA) | ★★★★☆ | @CreatedBy<br>private String creator; |
| JPA | @LastModifiedBy |
自动设置最后修改者(Spring Data JPA) | ★★★★☆ | @LastModifiedBy<br>private String updater; |
| JPA | @Version |
乐观锁版本字段 | ★★★★☆ | @Version<br>private Integer version; |
| JPA | @DynamicInsert |
Hibernate:动态插入(只插入非空字段) | ★★★☆☆ | @Entity<br>@DynamicInsert<br>public class User { ... } |
| JPA | @DynamicUpdate |
Hibernate:动态更新(只更新变化的字段) | ★★★★☆ | @Entity<br>@DynamicUpdate<br>public class User { ... } |
| JPA | @SelectBeforeUpdate |
Hibernate:更新前先查询 | ★★☆☆☆ | @Entity<br>@SelectBeforeUpdate<br>public class User { ... } |
| JPA | @Where |
Hibernate:实体级的where条件 | ★★★☆☆ | @Entity<br>@Where(clause="deleted = false")<br>public class User { ... } |
| JPA | @Filter |
Hibernate:动态过滤器 | ★★☆☆☆ | @Filter(name="activeFilter", condition="active = :active") |
| JPA | @Formula |
Hibernate:数据库公式字段 | ★★★☆☆ | @Formula("(SELECT COUNT(*) FROM orders o WHERE o.user_id = id)")<br>private Integer orderCount; |
| JPA | @NaturalId |
Hibernate:自然ID(业务唯一标识) | ★★★☆☆ | @NaturalId<br>private String email; |
四、MyBatis注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| MyBatis | @Mapper |
标记为MyBatis映射器接口 | ★★★★★ | @Mapper<br>public interface UserMapper { ... } |
| MyBatis | @Select |
查询SQL注解 | ★★★★★ | @Select("SELECT * FROM user WHERE id = #{id}")<br>User selectById(Long id); |
| MyBatis | @Insert |
插入SQL注解 | ★★★★★ | @Insert("INSERT INTO user(name, age) VALUES(#{name}, #{age})")<br>int insert(User user); |
| MyBatis | @Update |
更新SQL注解 | ★★★★★ | @Update("UPDATE user SET name=#{name} WHERE id=#{id}")<br>int update(User user); |
| MyBatis | @Delete |
删除SQL注解 | ★★★★★ | @Delete("DELETE FROM user WHERE id=#{id}")<br>int delete(Long id); |
| MyBatis | @Results |
结果集映射 | ★★★★★ | @Results({<br>@Result(property="id", column="user_id", id=true),<br>@Result(property="name", column="user_name")<br>}) |
| MyBatis | @Result |
单字段结果映射 | ★★★★★ | @Result(property="userId", column="id", id=true) |
| MyBatis | @Param |
参数名映射(多参数时必须) | ★★★★★ | List<User> selectByName(@Param("username") String name, @Param("status") Integer status); |
| MyBatis | @Options |
配置选项(如自增主键) | ★★★★★ | @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")<br>@Insert("INSERT INTO user(name) VALUES(#{name})")<br>int insert(User user); |
| MyBatis | @SelectProvider |
动态SQL提供类(Select) | ★★★★☆ | @SelectProvider(type=UserSqlProvider.class, method="selectByName")<br>List<User> selectByName(String name); |
| MyBatis | @InsertProvider |
动态SQL提供类(Insert) | ★★★★☆ | @InsertProvider(type=UserSqlProvider.class, method="insert")<br>int insert(User user); |
| MyBatis | @UpdateProvider |
动态SQL提供类(Update) | ★★★★☆ | @UpdateProvider(type=UserSqlProvider.class, method="update")<br>int update(User user); |
| MyBatis | @DeleteProvider |
动态SQL提供类(Delete) | ★★★★☆ | @DeleteProvider(type=UserSqlProvider.class, method="delete")<br>int delete(Long id); |
| MyBatis | @MapperScan |
扫描Mapper接口(配置类使用) | ★★★★★ | @Configuration<br>@MapperScan("com.example.mapper")<br>public class MyBatisConfig {} |
| MyBatis | @ResultMap |
引用已定义的Results映射 | ★★★★☆ | @ResultMap("userResultMap")<br>User selectById(Long id); |
| MyBatis | @One |
复杂对象一对一映射 | ★★★★☆ | @One(select="com.example.mapper.AddressMapper.selectByUserId")<br>private Address address; |
| MyBatis | @Many |
复杂对象一对多映射 | ★★★★☆ | @Many(select="com.example.mapper.OrderMapper.selectByUserId")<br>private List<Order> orders; |
| MyBatis | @Lang |
使用自定义语言驱动 | ★☆☆☆☆ | @Lang(XMLLanguageDriver.class)<br>User selectUser(Long id); |
| MyBatis | @Flush |
调用SqlSession的flushStatements方法 | ★☆☆☆☆ | @Flush<br>List<BatchResult> flush(); |
| MyBatis | @ConstructorArgs |
构造器参数映射 | ★★★☆☆ | @ConstructorArgs({<br>@Arg(column="id", javaType=Long.class, id=true),<br>@Arg(column="name", javaType=String.class)<br>}) |
| MyBatis | @TypeDiscriminator |
类型鉴别器 | ★☆☆☆☆ | @TypeDiscriminator(column="type", javaType=String.class, cases={<br>@Case(value="1", type=Admin.class),<br>@Case(value="2", type=User.class)<br>}) |
| MyBatis | @CacheNamespace |
配置Mapper命名空间缓存 | ★★★☆☆ | @CacheNamespace(implementation=MybatisRedisCache.class, eviction=FifoCache.class)<br>public interface UserMapper { ... } |
五、Lombok注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Lombok | @Data |
生成getter、setter、equals、hashCode、toString | ★★★★★ | @Data<br>public class User { private Long id; private String name; } |
| Lombok | @Getter |
生成getter方法 | ★★★★★ | @Getter<br>private String name;<br><br>@Getter(lazy=true)<br>private final String heavyData = computeHeavyData(); |
| Lombok | @Setter |
生成setter方法 | ★★★★★ | @Setter<br>private String name;<br><br>@Setter(AccessLevel.PROTECTED)<br>private String name; |
| Lombok | @ToString |
生成toString方法 | ★★★★★ | @ToString(exclude="password", callSuper=true)<br>public class User { private String username; private String password; } |
| Lombok | @EqualsAndHashCode |
生成equals和hashCode方法 | ★★★★☆ | @EqualsAndHashCode(callSuper=true, exclude={"password"})<br>public class User extends BaseEntity { ... } |
| Lombok | @NoArgsConstructor |
生成无参构造器 | ★★★★★ | @NoArgsConstructor<br>public class User { ... } |
| Lombok | @AllArgsConstructor |
生成全参构造器 | ★★★★★ | @AllArgsConstructor<br>public class User { private Long id; private String name; } |
| Lombok | @RequiredArgsConstructor |
生成必需参数构造器(final字段和@NonNull字段) | ★★★★☆ | @RequiredArgsConstructor<br>public class User { private final Long id; @NonNull private String name; } |
| Lombok | @Builder |
生成建造者模式 | ★★★★★ | @Builder<br>@ToString<br>public class User { private Long id; private String name; } |
| Lombok | @Builder.Default |
Builder的默认值 | ★★★★☆ | @Builder.Default<br>private Integer status = 0; |
| Lombok | @Slf4j |
生成Slf4j日志对象 | ★★★★★ | @Slf4j<br>public class UserService { public void save() { log.info("保存用户"); } } |
| Lombok | @Log4j |
生成Log4j日志对象 | ★★☆☆☆ | @Log4j<br>public class UserService { ... } |
| Lombok | @Log4j2 |
生成Log4j2日志对象 | ★★★☆☆ | @Log4j2<br>public class UserService { ... } |
| Lombok | @CommonsLog |
生成Apache Commons Log日志对象 | ★★☆☆☆ | @CommonsLog<br>public class UserService { ... } |
| Lombok | @JBossLog |
生成JBoss Logging日志对象 | ★☆☆☆☆ | @JBossLog<br>public class UserService { ... } |
| Lombok | @Flogger |
生成Google Fluent Logger对象 | ★☆☆☆☆ | @Flogger<br>public class UserService { ... } |
| Lombok | @CustomLog |
自定义日志对象 | ★☆☆☆☆ | @CustomLog(topic="UserService")<br>public class UserService { ... } |
| Lombok | @Value |
生成不可变类(所有字段为private final) | ★★★★☆ | @Value<br>@Builder<br>public class User { Long id; String name; } |
| Lombok | @NonNull |
生成非空检查 | ★★★★☆ | public void setName(@NonNull String name) { this.name = name; } |
| Lombok | @Cleanup |
自动关闭资源(try-with-resources) | ★★★★☆ | @Cleanup<br>InputStream in = new FileInputStream("file"); |
| Lombok | @Synchronized |
同步方法(比synchronized更安全) | ★★☆☆☆ | @Synchronized<br>public void method() { ... } |
| Lombok | @SneakyThrows |
偷偷抛出异常(不用声明throws) | ★★★☆☆ | @SneakyThrows(IOException.class)<br>public void read() { ... } |
| Lombok | @With |
生成with方法(不可变对象的复制) | ★★★☆☆ | @With<br>private final String name;<br>// 生成:public User withName(String name) { ... } |
| Lombok | @UtilityClass |
工具类注解(私有构造器,静态方法) | ★★★☆☆ | @UtilityClass<br>public class StringUtils { ... } |
| Lombok | @FieldNameConstants |
生成字段常量(字段名作为字符串常量) | ★★☆☆☆ | @FieldNameConstants<br>public class User { private Long id; private String name; }<br>// 生成:Fields.id, Fields.name |
| Lombok | @FieldDefaults |
设置字段默认访问级别 | ★★☆☆☆ | @FieldDefaults(level=AccessLevel.PRIVATE, makeFinal=true)<br>public class User { Long id; String name; } |
| Lombok | @SuperBuilder |
支持父类的Builder模式 | ★★★☆☆ | @SuperBuilder<br>public class User extends BaseEntity { ... } |
六、测试相关注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 测试 | @Test |
JUnit测试方法 | ★★★★★ | @Test<br>public void testMethod() { assertEquals(2, 1+1); } |
| 测试 | @BeforeEach |
JUnit 5:每个测试前执行 | ★★★★★ | @BeforeEach<br>public void setUp() { // 初始化 } |
| 测试 | @AfterEach |
JUnit 5:每个测试后执行 | ★★★★★ | @AfterEach<br>public void tearDown() { // 清理 } |
| 测试 | @BeforeAll |
JUnit 5:所有测试前执行 | ★★★★★ | @BeforeAll<br>public static void initAll() { // 全局初始化 } |
| 测试 | @AfterAll |
JUnit 5:所有测试后执行 | ★★★★★ | @AfterAll<br>public static void tearDownAll() { // 全局清理 } |
| 测试 | @Before |
JUnit 4:每个测试前执行 | ★★★☆☆ | @Before<br>public void setUp() { ... } |
| 测试 | @After |
JUnit 4:每个测试后执行 | ★★★☆☆ | @After<br>public void tearDown() { ... } |
| 测试 | @BeforeClass |
JUnit 4:所有测试前执行 | ★★★☆☆ | @BeforeClass<br>public static void initClass() { ... } |
| 测试 | @AfterClass |
JUnit 4:所有测试后执行 | ★★★☆☆ | @AfterClass<br>public static void tearDownClass() { ... } |
| 测试 | @Disabled |
禁用测试方法或类 | ★★★★☆ | @Disabled("暂时禁用,待修复")<br>@Test<br>public void brokenTest() { ... } |
| 测试 | @DisplayName |
为测试类或方法设置显示名称 | ★★★★☆ | @DisplayName("测试用户服务")<br>class UserServiceTest { ... } |
| 测试 | @RepeatedTest |
重复测试 | ★★★☆☆ | @RepeatedTest(5)<br>public void repeatedTest() { ... } |
| 测试 | @ParameterizedTest |
参数化测试 | ★★★★☆ | @ParameterizedTest<br>@ValueSource(strings={"a", "b", "c"})<br>public void testWithValueSource(String value) { ... } |
| 测试 | @TestFactory |
动态测试工厂 | ★★☆☆☆ | @TestFactory<br>public Stream<DynamicTest> dynamicTests() { ... } |
| 测试 | @Nested |
嵌套测试类 | ★★★☆☆ | @Nested<br>class WhenUserExists { ... } |
| 测试 | @Tag |
为测试方法或类添加标签 | ★★★☆☆ | @Tag("fast")<br>@Test<br>public void fastTest() { ... } |
| 测试 | @Timeout |
设置测试超时时间 | ★★★☆☆ | @Timeout(5)<br>@Test<br>public void timeoutTest() { ... } |
| 测试 | @SpringBootTest |
Spring Boot集成测试 | ★★★★★ | @SpringBootTest<br>@AutoConfigureMockMvc<br>class UserServiceTest { @Autowired private MockMvc mockMvc; } |
| 测试 | @WebMvcTest |
Spring MVC切片测试 | ★★★★★ | @WebMvcTest(UserController.class)<br>@AutoConfigureMockMvc<br>class UserControllerTest { ... } |
| 测试 | @DataJpaTest |
JPA切片测试 | ★★★★★ | @DataJpaTest<br>@AutoConfigureTestDatabase(replace=Replace.NONE)<br>class UserRepositoryTest { ... } |
| 测试 | @JdbcTest |
JDBC切片测试 | ★★☆☆☆ | @JdbcTest<br>class JdbcTestExample { ... } |
| 测试 | @JsonTest |
JSON序列化测试 | ★★★☆☆ | @JsonTest<br>class UserJsonTest { ... } |
| 测试 | @RestClientTest |
REST客户端测试 | ★★★☆☆ | @RestClientTest(UserService.class)<br>class UserServiceTest { ... } |
| 测试 | @MockBean |
Spring Boot模拟Bean | ★★★★★ | @MockBean<br>private UserService userService; |
| 测试 | @SpyBean |
Spring Boot监视Bean | ★★★☆☆ | @SpyBean<br>private UserService userService; |
| 测试 | @TestConfiguration |
测试配置类 | ★★★★☆ | @TestConfiguration<br>static class TestConfig { @Bean public DataSource testDataSource() { ... } } |
| 测试 | @TestPropertySource |
测试属性源 | ★★★★☆ | @TestPropertySource(locations="classpath:test.properties", properties="app.name=test") |
| 测试 | @ActiveProfiles |
激活配置文件 | ★★★★★ | @ActiveProfiles("dev")<br>@SpringBootTest<br>class DevTest { ... } |
| 测试 | @DirtiesContext |
标记测试会污染Spring上下文 | ★★★☆☆ | @DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD) |
| 测试 | @Sql |
执行SQL脚本 | ★★★☆☆ | @Sql(scripts="classpath:test-data.sql")<br>@Test<br>public void testWithData() { ... } |
| 测试 | @Transactional |
测试事务(默认回滚) | ★★★★☆ | @Transactional<br>@Test<br>public void transactionalTest() { ... } |
| 测试 | @Rollback |
控制测试事务是否回滚 | ★★★☆☆ | @Rollback(false)<br>@Test<br>public void testNoRollback() { ... } |
| 测试 | @Commit |
测试事务提交 | ★★★☆☆ | @Commit<br>@Test<br>public void testCommit() { ... } |
| 测试 | @Mock |
Mockito模拟对象 | ★★★★★ | @Mock<br>private UserDao userDao; |
| 测试 | @Spy |
Mockito监视真实对象 | ★★★★☆ | @Spy<br>private List<String> list = new ArrayList<>(); |
| 测试 | @InjectMocks |
Mockito注入模拟对象 | ★★★★★ | @InjectMocks<br>private UserService userService; |
| 测试 | @Captor |
Mockito参数捕获器 | ★★★★☆ | @Captor<br>private ArgumentCaptor<String> captor; |
| 测试 | @ExtendWith |
JUnit 5扩展 | ★★★★★ | @ExtendWith(MockitoExtension.class)<br>class UserServiceTest {} |
| 测试 | @TestInstance |
控制测试实例生命周期 | ★★☆☆☆ | @TestInstance(TestInstance.Lifecycle.PER_CLASS) |
| 测试 | @TestMethodOrder |
测试方法执行顺序 | ★★★☆☆ | @TestMethodOrder(MethodOrderer.OrderAnnotation.class) |
| 测试 | @Order |
测试方法顺序 | ★★★☆☆ | @Order(1)<br>@Test<br>public void firstTest() { ... } |
七、Swagger/OpenAPI注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| Swagger | @Api |
标记API类(Swagger 2) | ★★★★☆ | @Api(tags="用户管理", description="用户相关接口")<br>@RestController<br>public class UserController {} |
| Swagger | @ApiOperation |
描述API方法(Swagger 2) | ★★★★★ | @ApiOperation(value="根据ID获取用户", notes="需要用户ID", response=User.class)<br>@GetMapping("/{id}")<br>public User getById(@PathVariable Long id) {} |
| Swagger | @ApiParam |
描述API参数(Swagger 2) | ★★★★★ | @GetMapping("/{id}")<br>public User getById(@ApiParam(value="用户ID", required=true, example="123") @PathVariable Long id) {} |
| Swagger | @ApiModel |
描述数据模型(Swagger 2) | ★★★★★ | @ApiModel(description="用户实体", value="User")<br>public class User { ... } |
| Swagger | @ApiModelProperty |
描述模型属性(Swagger 2) | ★★★★★ | @ApiModelProperty(value="用户姓名", required=true, example="张三", position=1)<br>private String name; |
| Swagger | @ApiIgnore |
忽略API文档生成(Swagger 2) | ★★★★☆ | @ApiIgnore<br>@GetMapping("/internal")<br>public String internalApi() {} |
| Swagger | @ApiResponse |
描述API响应(Swagger 2) | ★★★★☆ | @ApiResponse(code=200, message="成功", response=User.class) |
| Swagger | @ApiResponses |
描述多个API响应(Swagger 2) | ★★★★☆ | @ApiResponses({<br>@ApiResponse(code=200, message="成功"),<br>@ApiResponse(code=404, message="用户不存在")<br>}) |
| Swagger | @Authorization |
描述授权信息(Swagger 2) | ★★☆☆☆ | @Authorization(value="oauth2", scopes={@AuthorizationScope(...)}) |
| Swagger | @Tag |
OpenAPI 3.0的标签注解 | ★★★★★ | @Tag(name="用户管理", description="用户相关操作")<br>@RestController<br>public class UserController {} |
| Swagger | @Operation |
OpenAPI 3.0的操作注解 | ★★★★★ | @Operation(summary="根据ID获取用户", description="通过用户ID获取用户详细信息")<br>@GetMapping("/{id}")<br>public User getById(@PathVariable Long id) {} |
| Swagger | @Parameter |
OpenAPI 3.0的参数注解 | ★★★★★ | @Parameter(name="id", description="用户ID", required=true, example="123")<br>@PathVariable Long id |
| Swagger | @Schema |
OpenAPI 3.0的模式注解 | ★★★★★ | @Schema(description="用户实体", example="{\"id\":1,\"name\":\"张三\"}")<br>public class User { ... } |
| Swagger | @Schema |
OpenAPI 3.0的属性注解 | ★★★★★ | @Schema(description="用户姓名", example="张三", requiredMode=Schema.RequiredMode.REQUIRED)<br>private String name; |
| Swagger | @Hidden |
OpenAPI 3.0的隐藏注解 | ★★★★☆ | @Hidden<br>@GetMapping("/internal")<br>public String internalApi() {} |
| Swagger | @ArraySchema |
OpenAPI 3.0的数组模式注解 | ★★★☆☆ | @ArraySchema(schema=@Schema(implementation=User.class), maxItems=100) |
| Swagger | @Content |
OpenAPI 3.0的内容注解 | ★★★☆☆ | @Content(mediaType="application/json", schema=@Schema(implementation=User.class)) |
| Swagger | @ApiKeyAuthDefinition |
API密钥认证定义 | ★★★☆☆ | @ApiKeyAuthDefinition(name="apiKey", in=ApiKeyAuthDefinition.ApiKeyLocation.HEADER, key="X-API-KEY") |
| Swagger | @BasicAuthDefinition |
基本认证定义 | ★★☆☆☆ | @BasicAuthDefinition(type=SecuritySchemeType.HTTP, scheme="basic") |
| Swagger | @OAuth2Definition |
OAuth2认证定义 | ★★★☆☆ | @OAuth2Definition(flows=@OAuthFlows(implicit=@OAuthFlow(authorizationUrl="...", scopes={...}))) |
八、校验注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 校验 | @NotNull |
参数不能为null | ★★★★★ | @NotNull<br>private String name; |
| 校验 | @NotEmpty |
字符串/集合/数组不能为空(长度>0) | ★★★★★ | @NotEmpty<br>private String name;<br>@NotEmpty<br>private List<String> items; |
| 校验 | @NotBlank |
字符串不能为空且必须包含非空白字符 | ★★★★★ | @NotBlank<br>private String username; |
| 校验 | @Size |
校验字符串/集合长度 | ★★★★★ | @Size(min=2, max=10)<br>private String username;<br>@Size(min=1, max=100)<br>private List<String> items; |
| 校验 | @Email |
校验邮箱格式 | ★★★★★ | @Email<br>private String email; |
| 校验 | @Min |
数值最小值 | ★★★★★ | @Min(1)<br>private Integer age; |
| 校验 | @Max |
数值最大值 | ★★★★★ | @Max(150)<br>private Integer age; |
| 校验 | @DecimalMin |
小数最小值 | ★★★★☆ | @DecimalMin("0.0")<br>private BigDecimal price;<br>@DecimalMin(value="0.0", inclusive=false) // 严格大于0 |
| 校验 | @DecimalMax |
小数最大值 | ★★★★☆ | @DecimalMax("100.0")<br>private BigDecimal score; |
| 校验 | @Digits |
数字位数限制 | ★★★☆☆ | @Digits(integer=3, fraction=2)<br>private BigDecimal amount; // 整数3位,小数2位 |
| 校验 | @Pattern |
正则表达式校验 | ★★★★☆ | @Pattern(regexp="^[a-zA-Z0-9]{4,10}$")<br>private String username; |
| 校验 | @Positive |
正数(>0) | ★★★★☆ | @Positive<br>private Integer count; |
| 校验 | @PositiveOrZero |
正数或零(>=0) | ★★★★☆ | @PositiveOrZero<br>private Integer count; |
| 校验 | @Negative |
负数(<0) | ★★★☆☆ | @Negative<br>private Integer count; |
| 校验 | @NegativeOrZero |
负数或零(<=0) | ★★★☆☆ | @NegativeOrZero<br>private Integer count; |
| 校验 | @Past |
过去日期 | ★★★★☆ | @Past<br>private Date birthDate;<br>@Past<br>private LocalDate birthDate; |
| 校验 | @PastOrPresent |
过去或现在日期 | ★★★☆☆ | @PastOrPresent<br>private Date date; |
| 校验 | @Future |
将来日期 | ★★★★☆ | @Future<br>private Date expireDate; |
| 校验 | @FutureOrPresent |
将来或现在日期 | ★★★☆☆ | @FutureOrPresent<br>private Date date; |
| 校验 | @AssertTrue |
必须为true | ★★★☆☆ | @AssertTrue<br>private boolean acceptedTerms; |
| 校验 | @AssertFalse |
必须为false | ★★★☆☆ | @AssertFalse<br>private boolean invalid; |
| 校验 | @Valid |
级联校验 | ★★★★★ | @Valid<br>private Address address;<br>@Valid<br>private List<OrderItem> items; |
| 校验 | @Null |
必须为null | ★★☆☆☆ | @Null<br>private String unusedField; |
| 校验 | @Length |
Hibernate Validator:字符串长度 | ★★★★☆ | @Length(min=2, max=10)<br>private String username; |
| 校验 | @Range |
Hibernate Validator:数值范围 | ★★★★☆ | @Range(min=1, max=150)<br>private Integer age; |
| 校验 | @URL |
Hibernate Validator:URL格式 | ★★★☆☆ | @URL<br>private String website; |
| 校验 | @SafeHtml |
Hibernate Validator:安全HTML | ★☆☆☆☆ | @SafeHtml<br>private String content; |
| 校验 | @CreditCardNumber |
Hibernate Validator:信用卡号 | ★☆☆☆☆ | @CreditCardNumber<br>private String cardNumber; |
| 校验 | @ScriptAssert |
脚本断言 | ★★☆☆☆ | @ScriptAssert(lang="javascript", script="...")<br>public class User { ... } |
九、JSON处理注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| JSON | @JsonIgnore |
JSON序列化时忽略字段 | ★★★★★ | @JsonIgnore<br>private String password; |
| JSON | @JsonProperty |
指定JSON字段名 | ★★★★★ | @JsonProperty("user_name")<br>private String username;<br>@JsonProperty(access=JsonProperty.Access.READ_ONLY)<br>private Long id; |
| JSON | @JsonFormat |
日期格式序列化 | ★★★★★ | @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss", timezone="GMT+8")<br>private Date createTime;<br>@JsonFormat(shape=JsonFormat.Shape.STRING)<br>private BigDecimal amount; |
| JSON | @JsonInclude |
控制序列化时包含的属性 | ★★★★★ | @JsonInclude(JsonInclude.Include.NON_NULL)<br>public class User { ... }<br>@JsonInclude(JsonInclude.Include.NON_EMPTY)<br>private List<String> items; |
| JSON | @JsonSerialize |
自定义序列化器 | ★★★☆☆ | @JsonSerialize(using=CustomDateSerializer.class)<br>private Date customDate; |
| JSON | @JsonDeserialize |
自定义反序列化器 | ★★★☆☆ | @JsonDeserialize(using=CustomDateDeserializer.class)<br>private Date customDate; |
| JSON | @JsonTypeInfo |
多态类型处理 | ★★★☆☆ | @JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")<br>private Animal animal; |
| JSON | @JsonSubTypes |
多态子类型映射 | ★★★☆☆ | @JsonSubTypes({<br>@JsonSubTypes.Type(value=Dog.class, name="dog"),<br>@JsonSubTypes.Type(value=Cat.class, name="cat")<br>})<br>public abstract class Animal { ... } |
| JSON | @JsonIdentityInfo |
处理循环引用 | ★★★☆☆ | @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")<br>public class User { ... } |
| JSON | @JsonView |
视图控制 | ★★★★☆ | public class Views {<br>public static class Public { }<br>public static class Internal extends Public { }<br>}<br>@JsonView(Views.Public.class)<br>private String name;<br>@JsonView(Views.Internal.class)<br>private String email; |
| JSON | @JsonUnwrapped |
展开嵌套对象 | ★★★☆☆ | @JsonUnwrapped<br>private Address address; // {city:"...", street:"..."} |
| JSON | @JsonManagedReference |
处理双向关系(父端) | ★★★☆☆ | @JsonManagedReference<br>private List<Order> orders; |
| JSON | @JsonBackReference |
处理双向关系(子端) | ★★★☆☆ | @JsonBackReference<br>private User user; |
| JSON | @JsonNaming |
命名策略 | ★★★☆☆ | @JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)<br>public class User { private String userName; } // 序列化为 user_name |
| JSON | @JsonPropertyOrder |
属性顺序 | ★★☆☆☆ | @JsonPropertyOrder({"id", "name", "email"})<br>public class User { ... } |
| JSON | @JsonAnyGetter |
动态属性getter | ★★☆☆☆ | @JsonAnyGetter<br>public Map<String, Object> getProperties() { ... } |
| JSON | @JsonAnySetter |
动态属性setter | ★★☆☆☆ | @JsonAnySetter<br>public void setProperty(String key, Object value) { ... } |
| JSON | @JsonGetter |
自定义getter方法名 | ★☆☆☆☆ | @JsonGetter("userName")<br>public String getUsername() { return username; } |
| JSON | @JsonSetter |
自定义setter方法名 | ★☆☆☆☆ | @JsonSetter("userName")<br>public void setUsername(String username) { this.username = username; } |
| JSON | @JsonRawValue |
原始JSON值 | ★★☆☆☆ | @JsonRawValue<br>private String json = "{\"key\":\"value\"}"; |
| JSON | @JsonValue |
序列化整个对象为一个值 | ★☆☆☆☆ | @JsonValue<br>public String toJson() { return ...; } |
| JSON | @JsonCreator |
反序列化构造器/工厂方法 | ★★★☆☆ | @JsonCreator<br>public User(@JsonProperty("id") Long id, @JsonProperty("name") String name) { ... } |
十、缓存注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 缓存 | @Cacheable |
缓存方法结果 | ★★★★★ | @Cacheable(value="users", key="#id", unless="#result == null")<br>public User findById(Long id) { ... } |
| 缓存 | @CacheEvict |
清除缓存 | ★★★★★ | @CacheEvict(value="users", key="#user.id")<br>public void update(User user) { ... }<br>@CacheEvict(value="users", allEntries=true)<br>public void clearCache() { ... } |
| 缓存 | @CachePut |
更新缓存 | ★★★★☆ | @CachePut(value="users", key="#user.id")<br>public User update(User user) { ... } |
| 缓存 | @Caching |
组合多个缓存操作 | ★★★☆☆ | @Caching(<br>cacheable={@Cacheable(value="users", key="#name")},<br>evict={@CacheEvict(value="allUsers", allEntries=true)}<br>)<br>public User findByName(String name) { ... } |
| 缓存 | @CacheConfig |
类级别缓存配置 | ★★★★☆ | @CacheConfig(cacheNames="users")<br>public class UserService { ... } |
十一、定时任务注解 ★★★★☆
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 定时 | @Scheduled |
定时任务 | ★★★★★ | @Scheduled(cron="0 0 12 * * ?")<br>public void dailyTask() { ... }<br>@Scheduled(fixedRate=5000)<br>public void fixedRateTask() { ... }<br>@Scheduled(fixedDelay=5000)<br>public void fixedDelayTask() { ... } |
| 定时 | @EnableScheduling |
启用定时任务 | ★★★★★ | @SpringBootApplication<br>@EnableScheduling<br>public class Application { ... } |
| 定时 | @Async |
异步方法 | ★★★★★ | @Async("taskExecutor")<br>public CompletableFuture<User> findUser(Long id) { ... } |
| 定时 | @EnableAsync |
启用异步支持 | ★★★★★ | @Configuration<br>@EnableAsync<br>public class AsyncConfig { ... } |
| 定时 | @Schedules |
多个@Schedule注解 | ★★☆☆☆ | @Schedules({<br>@Scheduled(cron="0 0 9 * * ?"),<br>@Scheduled(cron="0 0 18 * * ?")<br>})<br>public void scheduledTask() { ... } |
十二、AOP注解 ★★★★☆
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| AOP | @Aspect |
声明切面类 | ★★★★★ | @Aspect<br>@Component<br>public class LogAspect { ... } |
| AOP | @Before |
前置通知 | ★★★★★ | @Before("execution(* com.example.service.*.*(..))")<br>public void beforeAdvice(JoinPoint joinPoint) { ... } |
| AOP | @After |
后置通知(finally) | ★★★★★ | @After("execution(* com.example.service.*.*(..))")<br>public void afterAdvice(JoinPoint joinPoint) { ... } |
| AOP | @AfterReturning |
返回后通知 | ★★★★☆ | @AfterReturning(pointcut="execution(* com.example.service.*.*(..))", returning="result")<br>public void afterReturningAdvice(JoinPoint joinPoint, Object result) { ... } |
| AOP | @AfterThrowing |
异常后通知 | ★★★★☆ | @AfterThrowing(pointcut="execution(* com.example.service.*.*(..))", throwing="ex")<br>public void afterThrowingAdvice(JoinPoint joinPoint, Exception ex) { ... } |
| AOP | @Around |
环绕通知 | ★★★★★ | @Around("execution(* com.example.service.*.*(..))")<br>public Object aroundAdvice(ProceedingJoinPoint pjp) throws Throwable { ... } |
| AOP | @Pointcut |
定义切点表达式 | ★★★★★ | @Pointcut("execution(* com.example.service.*.*(..))")<br>public void serviceLayer() {}<br>@Before("serviceLayer()")<br>public void beforeService() { ... } |
| AOP | @EnableAspectJAutoProxy |
启用AspectJ自动代理 | ★★★★☆ | @Configuration<br>@EnableAspectJAutoProxy(proxyTargetClass=true)<br>public class AopConfig { ... } |
| AOP | @DeclareParents |
引入通知(引入新接口) | ★★☆☆☆ | @DeclareParents(value="com.example.service.*+", defaultImpl=DefaultUsageTracked.class)<br>public static UsageTracked mixin; |
| AOP | @Order |
切面执行顺序 | ★★★★☆ | @Aspect<br>@Order(1)<br>@Component<br>public class FirstAspect { ... } |
十三、消息队列注解 ★★★☆☆
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| MQ | @RabbitListener |
RabbitMQ监听器 | ★★★★☆ | @RabbitListener(queues="myQueue")<br>public void processMessage(String message) { ... }<br>@RabbitListener(bindings=@QueueBinding(<br>value=@Queue(value="myQueue", durable="true"),<br>exchange=@Exchange(value="myExchange", type="direct"),<br>key="myRoutingKey"))<br>public void processMessage(Message message) { ... } |
| MQ | @RabbitHandler |
RabbitMQ消息处理方法 | ★★★☆☆ | @RabbitListener(queues="myQueue")<br>public class MessageHandler {<br>@RabbitHandler<br>public void handleString(String message) { ... }<br>@RabbitHandler<br>public void handleJson(User user) { ... }<br>} |
| MQ | @KafkaListener |
Kafka监听器 | ★★★★☆ | @KafkaListener(topics="myTopic", groupId="myGroup")<br>public void listen(String message) { ... }<br>@KafkaListener(topics="myTopic", groupId="myGroup", concurrency="3")<br>public void listen(ConsumerRecord<String, String> record) { ... } |
| MQ | @EnableRabbit |
启用RabbitMQ支持 | ★★★☆☆ | @Configuration<br>@EnableRabbit<br>public class RabbitConfig { ... } |
| MQ | @EnableKafka |
启用Kafka支持 | ★★★☆☆ | @Configuration<br>@EnableKafka<br>public class KafkaConfig { ... } |
| MQ | @RabbitListener |
方法级重试 | ★★★☆☆ | @RabbitListener(queues="myQueue",<br>containerFactory="retryContainerFactory")<br>public void processWithRetry(String message) { ... } |
| MQ | @Payload |
获取消息体 | ★★★☆☆ | @KafkaListener(topics="myTopic")<br>public void listen(@Payload String data, @Header(KafkaHeaders.RECEIVED_MESSAGE_KEY) String key) { ... } |
十四、安全注解 ★★★★★
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 安全 | @EnableWebSecurity |
启用Web安全配置 | ★★★★★ | @Configuration<br>@EnableWebSecurity<br>public class SecurityConfig extends WebSecurityConfigurerAdapter { ... } |
| 安全 | @EnableGlobalMethodSecurity |
启用全局方法安全 | ★★★★★ | @Configuration<br>@EnableGlobalMethodSecurity(prePostEnabled=true, securedEnabled=true, jsr250Enabled=true)<br>public class MethodSecurityConfig { ... } |
| 安全 | @PreAuthorize |
方法调用前授权检查 | ★★★★★ | @PreAuthorize("hasRole('ADMIN') or #username == authentication.name")<br>public User findUser(String username) { ... } |
| 安全 | @PostAuthorize |
方法调用后授权检查 | ★★★★☆ | @PostAuthorize("returnObject.owner == authentication.name")<br>public User findUser(Long id) { ... } |
| 安全 | @Secured |
基于角色的安全注解 | ★★★★☆ | @Secured({"ROLE_ADMIN", "ROLE_USER"})<br>public void deleteUser(Long id) { ... } |
| 安全 | @RolesAllowed |
JSR-250角色允许注解 | ★★★☆☆ | @RolesAllowed({"ADMIN", "USER"})<br>public void updateUser(User user) { ... } |
| 安全 | @PermitAll |
JSR-250允许所有访问 | ★★★☆☆ | @PermitAll<br>public User getPublicInfo(Long id) { ... } |
| 安全 | @DenyAll |
JSR-250拒绝所有访问 | ★★☆☆☆ | @DenyAll<br>public void secretMethod() { ... } |
| 安全 | @PreFilter |
方法调用前过滤集合参数 | ★★★☆☆ | @PreFilter(filterTarget="users", value="filterObject.owner == authentication.name")<br>public void updateUsers(List<User> users) { ... } |
| 安全 | @PostFilter |
方法调用后过滤返回值 | ★★★☆☆ | @PostFilter("filterObject.owner == authentication.name")<br>public List<User> findAllUsers() { ... } |
| 安全 | @AuthenticationPrincipal |
注入当前认证用户 | ★★★★★ | @GetMapping("/profile")<br>public UserProfile getProfile(@AuthenticationPrincipal UserDetails userDetails) { ... } |
| 安全 | @CurrentSecurityContext |
注入当前安全上下文 | ★★★☆☆ | public void method(@CurrentSecurityContext SecurityContext context) { ... } |
| 安全 | @WithMockUser |
测试时模拟用户 | ★★★★☆ | @WithMockUser(username="admin", roles={"ADMIN"})<br>@Test<br>public void testAdminEndpoint() { ... } |
| 安全 | @WithUserDetails |
测试时模拟用户详情 | ★★★☆☆ | @WithUserDetails(value="user1", userDetailsServiceBeanName="myUserDetailsService")<br>@Test<br>public void testWithUserDetails() { ... } |
| 安全 | @WithAnonymousUser |
测试时模拟匿名用户 | ★★★☆☆ | @WithAnonymousUser<br>@Test<br>public void testAnonymousAccess() { ... } |
| 安全 | @WithSecurityContext |
自定义安全上下文 | ★★☆☆☆ | @WithSecurityContext(factory=WithMockCustomUserSecurityContextFactory.class)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface WithMockCustomUser { ... } |
十五、微服务注解 ★★★★☆
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 微服务 | @EnableDiscoveryClient |
启用服务发现客户端(Eureka/Consul等) | ★★★★★ | @SpringBootApplication<br>@EnableDiscoveryClient<br>public class UserServiceApplication { ... } |
| 微服务 | @EnableFeignClients |
启用Feign客户端 | ★★★★★ | @SpringBootApplication<br>@EnableFeignClients(basePackages="com.example.clients")<br>public class Application { ... } |
| 微服务 | @FeignClient |
声明Feign客户端 | ★★★★★ | @FeignClient(name="user-service", url="${user.service.url}", fallback=UserServiceFallback.class)<br>public interface UserServiceClient {<br>@GetMapping("/users/{id}")<br>User getUser(@PathVariable("id") Long id);<br>} |
| 微服务 | @LoadBalanced |
启用负载均衡 | ★★★★★ | @Bean<br>@LoadBalanced<br>public RestTemplate restTemplate() { return new RestTemplate(); } |
| 微服务 | @EnableCircuitBreaker |
启用断路器(Hystrix) | ★★★★☆ | @SpringBootApplication<br>@EnableCircuitBreaker<br>public class Application { ... } |
| 微服务 | @HystrixCommand |
Hystrix命令注解 | ★★★★☆ | @HystrixCommand(fallbackMethod="fallbackGetUser",<br>commandProperties={<br>@HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds", value="3000")<br>})<br>public User getUser(Long id) { ... } |
| 微服务 | @HystrixProperty |
Hystrix属性配置 | ★★★☆☆ | @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value="20") |
| 微服务 | @EnableHystrixDashboard |
启用Hystrix仪表盘 | ★★★☆☆ | @SpringBootApplication<br>@EnableHystrixDashboard<br>public class HystrixDashboardApplication { ... } |
| 微服务 | @EnableZuulProxy |
启用Zuul代理 | ★★★☆☆ | @SpringBootApplication<br>@EnableZuulProxy<br>public class GatewayApplication { ... } |
| 微服务 | @RefreshScope |
配置刷新作用域 | ★★★★☆ | @RestController<br>@RefreshScope<br>public class ConfigController {<br>@Value("${config.message}")<br>private String message;<br>} |
| 微服务 | @ConfigurationProperties |
配置属性绑定(Spring Cloud) | ★★★★★ | @ConfigurationProperties(prefix="spring.cloud.config")<br>public class ConfigClientProperties { ... } |
| 微服务 | @EnableConfigServer |
启用配置服务器 | ★★☆☆☆ | @SpringBootApplication<br>@EnableConfigServer<br>public class ConfigServerApplication { ... } |
| 微服务 | @EnableBinding |
Spring Cloud Stream:绑定消息通道 | ★★★☆☆ | @EnableBinding(Source.class)<br>public class MessageProducer { ... } |
| 微服务 | @StreamListener |
Spring Cloud Stream:消息监听 | ★★★☆☆ | @StreamListener(Sink.INPUT)<br>public void handleMessage(String message) { ... } |
| 微服务 | @Output |
Spring Cloud Stream:输出通道 | ★★★☆☆ | public interface Source {<br>@Output("outputChannel")<br>MessageChannel output();<br>} |
| 微服务 | @Input |
Spring Cloud Stream:输入通道 | ★★★☆☆ | public interface Sink {<br>@Input("inputChannel")<br>SubscribableChannel input();<br>} |
十六、工具类注解 ★★★☆☆
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 工具 | @UtilityClass |
Lombok工具类注解(私有构造器,静态方法) | ★★★☆☆ | @UtilityClass<br>public class StringUtils {<br>public boolean isEmpty(String str) { ... }<br>} |
| 工具 | @NonNullApi |
包级别非空注解 | ★★☆☆☆ | @NonNullApi<br>package com.example.service;<br>import org.springframework.lang.NonNullApi; |
| 工具 | @NonNullFields |
包级别非空字段注解 | ★★☆☆☆ | @NonNullFields<br>package com.example.model; |
| 工具 | @NonNull |
Spring非空注解 | ★★★★☆ | public User create(@NonNull String username, @NonNull String email) { ... } |
| 工具 | @Nullable |
可为空注解 | ★★★★☆ | @Nullable<br>public User findUser(Long id) { ... } // 可能返回null |
| 工具 | @Generated |
标记生成的代码 | ★★☆☆☆ | @Generated("com.example.Generator")<br>public class GeneratedClass { ... } |
| 工具 | @SuppressFBWarnings |
FindBugs警告抑制 | ★★☆☆☆ | @SuppressFBWarnings("EI_EXPOSE_REP")<br>public byte[] getData() { return data; } |
| 工具 | @CheckReturnValue |
错误检查:检查返回值 | ★☆☆☆☆ | @CheckReturnValue<br>public String process(String input) { ... } // 调用者应检查返回值 |
| 工具 | @ParametersAreNonnullByDefault |
参数非空默认值 | ★★☆☆☆ | @ParametersAreNonnullByDefault<br>public class UserService {<br>public void save(String username) { ... } // username不能为null<br>} |
十七、其他重要注解
国际化注解
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 国际化 | @DateTimeFormat |
日期时间格式化 | ★★★★☆ | @DateTimeFormat(pattern="yyyy-MM-dd")<br>private Date birthDate; |
| 国际化 | @NumberFormat |
数字格式化 | ★★★☆☆ | @NumberFormat(pattern="#,###.##")<br>private BigDecimal amount; |
| 国际化 | @DateTimeFormat |
Spring MVC参数绑定 | ★★★★☆ | @GetMapping("/search")<br>public List<User> search(@DateTimeFormat(iso=ISO.DATE) Date startDate) { ... } |
监控/度量注解
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 监控 | @Timed |
Micrometer计时注解 | ★★★☆☆ | @Timed(value="user.create", description="创建用户耗时")<br>public User createUser(User user) { ... } |
| 监控 | @Counted |
Micrometer计数注解 | ★★★☆☆ | @Counted(value="user.requests", description="用户请求次数")<br>public User getUser(Long id) { ... } |
| 监控 | @Metered |
Dropwizard Metrics计量注解 | ★★☆☆☆ | @Metered(name="requests")<br>public void handleRequest() { ... } |
| 监控 | @Gauge |
Dropwizard Metrics仪表注解 | ★★☆☆☆ | @Gauge(name="queue.size")<br>public int getQueueSize() { return queue.size(); } |
| 监控 | @CachedGauge |
Dropwizard Metrics缓存仪表 | ★☆☆☆☆ | @CachedGauge(name="database.connections", timeout=30, timeoutUnit=TimeUnit.SECONDS)<br>public int getActiveConnections() { ... } |
自定义注解示例
| 类别 | 注解 | 解释 | 常用程度 | 简单示例 |
|---|---|---|---|---|
| 自定义 | @interface |
定义自定义注解 | ★★★★☆ | @Target(ElementType.METHOD)<br>@Retention(RetentionPolicy.RUNTIME)<br>public @interface LogExecutionTime {<br>String value() default "";<br>LogLevel level() default LogLevel.INFO;<br>} |
| 自定义 | @AliasFor |
为注解属性定义别名 | ★★★☆☆ | @Retention(RetentionPolicy.RUNTIME)<br>@Target(ElementType.METHOD)<br>public @interface MyMapping {<br>@AliasFor(annotation=RequestMapping.class, attribute="path")<br>String[] value() default {};<br>} |
总结与最佳实践
常用程度说明:
- ★★★★★:必须掌握,日常开发几乎每天都会用到
- ★★★★☆:经常使用,在特定场景下频繁使用
- ★★★☆☆:偶尔使用,特定功能或框架需要时使用
- ★★☆☆☆:很少使用,特殊场景或遗留代码中使用
- ★☆☆☆☆:几乎不用,了解即可
使用建议:
- 避免过度注解:过多的注解会使代码难以阅读和维护
- 理解注解原理:了解注解背后的实现机制,避免误用
- 版本兼容性:注意不同框架版本的注解差异
- 性能考虑:反射注解可能影响性能,合理使用
- 文档化:为自定义注解编写清晰的文档和使用示例
常见注解组合:
java
// Spring Boot + JPA + Lombok 实体类
@Entity
@Table(name = "users")
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = true)
public class User extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(unique = true, nullable = false)
@NotBlank
@Size(min = 3, max = 50)
private String username;
@Email
@Column(unique = true)
private String email;
@JsonIgnore
private String password;
@CreatedDate
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
}
// Spring Boot + MyBatis + Swagger Controller
@RestController
@RequestMapping("/api/v1/users")
@Api(tags = "用户管理")
@Slf4j
@RequiredArgsConstructor
public class UserController {
private final UserService userService;
@GetMapping("/{id}")
@ApiOperation("根据ID获取用户")
public Result<UserDTO> getById(
@PathVariable @ApiParam("用户ID") Long id) {
return Result.success(userService.getById(id));
}
@PostMapping
@ApiOperation("创建用户")
@Transactional
public Result<Long> create(
@Valid @RequestBody @ApiParam("用户信息") UserCreateRequest request) {
log.info("创建用户: {}", request.getUsername());
return Result.success(userService.create(request));
}
}