Springboot 常用注解是?
时间: 2025-05-28 12:22:34 浏览: 10
### SpringBoot 常用注解列表及功能说明
SpringBoot 提供了许多强大的注解,用于简化开发流程并提高代码的可维护性。以下是常见的一些注解及其功能描述:
#### 1. `@SpringBootApplication`
这是 Spring Boot 应用的核心注解之一,它实际上是一个复合注解,包含了以下几个重要部分:
- `@EnableAutoConfiguration`: 启用了 Spring Boot 的自动配置机制[^2]。
- `@ComponentScan`: 扫描指定包路径下的所有组件,默认扫描当前类所在的包及其子包内的 Bean 定义。
- `@Configuration`: 将该类标记为一个配置类,意味着它可以被 Spring 容器识别并加载。
示例代码如下:
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
---
#### 2. `@Controller`, `@RestController`
这两个注解都用于定义控制器层的类,区别在于返回值形式的不同:
- `@Controller`:通常与视图解析器一起工作,适用于传统的 MVC 架构,返回的是视图名。
- `@RestController`:专门用于 RESTful API 开发,直接返回 JSON 或 XML 数据格式。
示例代码:
```java
@RestController
@RequestMapping("/api/users")
public class UserController {
@GetMapping("/{id}")
public ResponseEntity<User> getUserById(@PathVariable Long id) {
// 查询逻辑...
return ResponseEntity.ok(new User());
}
}
```
---
#### 3. `@Service`, `@Repository`, `@Component`
这三个注解均属于 Spring 的核心注解,主要用于声明不同层次的服务或组件:
- `@Service`:标注服务层的类,负责业务逻辑处理。
- `@Repository`:标注数据访问层的类,通常是 DAO 层或者 Repository 接口实现。
- `@Component`:泛型注解,可用于任何需要注册到 Spring 容器中的类。
示例代码:
```java
@Service
public class UserService {
private final UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public List<User> getAllUsers() {
return userRepository.findAll();
}
}
```
---
#### 4. `@Autowired`, `@Qualifier`
- `@Autowired`:用于自动装配依赖项,可以应用于构造函数、字段或方法上。默认按照类型进行匹配[^4]。
- `@Qualifier`:当存在多个相同类型的 Bean 时,可通过此注解指定具体的 Bean 名称。
示例代码:
```java
@Component
public class EmailSender implements MessageSender {}
@Component
public class SmsSender implements MessageSender {}
@Service
public class NotificationService {
@Autowired
@Qualifier("emailSender") // 明确指定使用哪个 Bean
private MessageSender sender;
public void sendMessage(String message) {
sender.send(message);
}
}
```
---
#### 5. `@Configuration`, `@Bean`
- `@Configuration`:将某个类标记为配置类,替代传统 XML 文件的作用[^3]。
- `@Bean`:用于在配置类中显式定义一个 Bean 并将其注册到 Spring 容器中。
示例代码:
```java
@Configuration
public class AppConfig {
@Bean
public MessageProcessor processor() {
return new DefaultMessageProcessor();
}
}
```
---
#### 6. `@Value`, `@PropertySource`
- `@Value`:从外部配置文件(如 properties/yaml)中读取属性值,并赋值给类的字段。
- `@PropertySource`:用于加载自定义的 `.properties` 文件,但不支持 YAML 格式的文件[^5]。
示例代码:
```java
@Component
@PropertySource("classpath:app-config.properties")
public class ConfigReader {
@Value("${app.name}")
private String appName;
public String getAppName() {
return appName;
}
}
```
---
#### 7. `@Scheduled`
用于定时任务调度,可以直接在方法上添加此注解来定义周期性的操作。
示例代码:
```java
@Component
public class ScheduledTasks {
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
System.out.println("The time is now " + LocalDateTime.now());
}
}
```
---
#### 8. `@Transactional`
用于事务管理,常用于服务层的方法上,确保一组数据库操作要么全部成功提交,要么回滚失败的部分。
示例代码:
```java
@Service
@Transactional
public class OrderService {
public void placeOrder(Order order) throws Exception {
// 插入订单记录
// 更新库存数量
}
}
```
---
#### 9. `@ConditionalOn*` 系列注解
这一组注解用于控制某些 Bean 是否应该被加载到容器中,具体取决于特定条件是否成立。例如:
- `@ConditionalOnClass`:只有当类路径中存在某类时才生效。
- `@ConditionalOnMissingBean`:仅在容器中不存在某种类型的 Bean 时才会创建新的 Bean。
示例代码:
```java
@Configuration
@ConditionalOnClass(name = "com.example.MyCustomLibrary")
public class ConditionalConfig {
@Bean
public CustomFeature customFeature() {
return new CustomFeature();
}
}
```
---
#### 10. `@Enable*` 系列注解
这类注解用于开启某些特殊功能的支持,比如缓存 (`@EnableCaching`)、异步调用 (`@EnableAsync`) 等。
示例代码:
```java
@EnableScheduling
public class SchedulingConfig {}
```
---
###
阅读全文
相关推荐







