📌 1. JDK 内置注解
示例代码
// @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 注解
示例代码
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 注解
示例代码
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 管理和配置。
💡 示例:
@Configuration
@ComponentScan("com.example") // 自动扫描指定包下的组件
public class AppConfig {
@Bean
public CoffeeMachine coffeeMachine() {
return new CoffeeMachine();
}
}
🛠 2. Spring 依赖注入(DI)相关注解
Spring 允许你自动注入 Bean,而不需要 new
关键字。
💡 示例:
@Component
public class CoffeeShop {
@Autowired
private CoffeeMachine coffeeMachine;
public void serve() {
coffeeMachine.brew();
}
}
📌 3. Bean 作用域 & 生命周期管理
Spring 提供了不同的 作用域(Scope),并允许你控制 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 请求。
💡 示例:
@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
public class CoffeeApplication {
public static void main(String[] args) {
SpringApplication.run(CoffeeApplication.class, args);
}
}
🗄 6. Spring 数据访问(JPA, MyBatis)
Spring 也能帮你简化数据库操作。
💡 示例:
@Entity
@Table(name="coffee")
public class Coffee {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
}
🎯 总结
学长,快收好这份 Spring & Spring Boot 注解大全!📜 这下你写 Spring 代码时,遇到问题就可以直接查这张表了!😏
哼,学长这次这么乖,叫我“小葵葵”,那我就大发慈悲给你整理个超清晰的分类表吧!😏
🌟 Spring / Spring Boot / Spring MVC 常用注解分层
🌟 终极总结
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 层)
💡 推荐实用技巧:
@CrossOrigin
解决跨域(前后端分离必备)
@RestController
代替@Controller + @ResponseBody
,少写代码
2️⃣ 业务层(Service 层)
💡 推荐实用技巧:
数据库操作时加
@Transactional
,避免数据不一致高并发接口加
@Async
,提高吞吐量数据查询接口加
@Cacheable
,减少数据库压力
3️⃣ 持久层(DAO 层 / Mapper 层)
💡 推荐实用技巧:
@Repository
+@Mapper
结合 MyBatis,数据库操作更清晰多用 XML 映射 SQL,减少
@Select
这种硬编码
4️⃣ 配置层
5️⃣ 依赖注入(IoC 容器)
💡 推荐实用技巧:
多用
@Autowired
,但在多个相同类型的 Bean 时用@Qualifier
@Value
读取配置,代替Properties
解析
6️⃣ AOP(面向切面编程)
💡 推荐实用技巧: 使用 AOP 进行
日志记录(请求耗时、请求参数)
权限校验(切到某个注解时拦截)
7️⃣ Spring Boot 相关
💡 推荐实用技巧: 使用
@Scheduled
进行定时任务,比如每天 0 点清理日志
8️⃣ Spring Security(权限相关)
💡 推荐实用技巧:
@PreAuthorize("hasRole('ADMIN')")
控制方法权限
@Secured
兼容老版本 Security
哼,学长连这种问题都要问我,果然还是离不开我呢~不过,既然你这么诚心诚意地请教我,我就大发慈悲地告诉你吧。
什么时候需要使用 @Bean
?
@Bean
主要用于 手动注册 Bean 到 Spring 容器,适用于以下几种情况:
当你无法修改源代码时
比如你使用的是 第三方库,而这个类没有
@Component
、@Service
这些注解,你又需要它被 Spring 容器管理时,就可以使用@Bean
来手动注册。示例
@Configuration public class MyConfig { @Bean public SomeThirdPartyService someThirdPartyService() { return new SomeThirdPartyService(); // 直接 new 一个实例 } }
需要自定义 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; } }
基于条件决定是否注册 Bean
如果你想在某些条件下才注册 Bean,比如 不同环境使用不同的 Bean,可以结合
@Conditional
一起用。示例
@Configuration public class MyConfig { @Bean @ConditionalOnProperty(name = "use.custom.service", havingValue = "true") public CustomService customService() { return new CustomService(); } }
什么时候不需要使用 @Bean
?
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 自动扫描。
依赖注入可以直接用
@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()); } }
Spring Boot 自动配置已经提供了 Bean
比如 Spring Boot 自动帮你注册了
DataSource
、RestTemplate
、ObjectMapper
等等,你不需要自己再@Bean
。错误示例(Spring Boot 已经提供了)
@Configuration public class MyConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); // 这个是多余的 } }
正确方式
@Autowired private RestTemplate restTemplate;