spring注解
spring注解
Spring 注解体系通过声明式编程简化了开发,覆盖了组件管理、依赖注入、Web 开发、数据访问、AOP、事务控制等场景。熟练掌握这些注解,能够显著提升代码的可读性和维护性。这里建议结合官方文档和实际项目需求,灵活选择适用的注解。
一、核心组件与依赖注入
@Component
- 作用:通用组件注解,声明类为 Spring 管理的 Bean。
- 示例:工具类、配置类等。
@Controller
作用:标记 Web 层控制器,处理 HTTP 请求。
示例
1
2@Controller
public class UserController { /* ... */ }
@Service
作用:标记业务逻辑层组件,封装业务逻辑。
示例
1
2@Service
public class UserService { /* ... */ }
@Repository
作用:标记数据访问层(DAO),处理数据库操作,自动转换持久层异常。
示例
1
2@Repository
public class UserDaoImpl implements UserDao { /* ... */ }
@Autowired
作用:按类型自动注入依赖,支持字段、构造器、方法注入。
示例
1
2@Autowired
private UserService userService;
@Qualifier
作用:与
@Autowired配合,按名称指定注入的 Bean。示例
1
2
3@Autowired
@Qualifier("userServiceImpl")
private UserService userService;
@Resource
作用:按名称注入依赖(JSR-250 标准)。
示例
1
2@Resource(name = "userDao")
private UserDao userDao;
@Value
作用:注入配置文件属性或表达式值。
示例
1
2@Value("${app.timeout:30}")
private int timeout;
@Scope
作用:定义 Bean 的作用域(如
singleton、prototype)。示例
1
2
3@Scope("prototype")
@Component
public class TaskProcessor { /* ... */ }
@Lazy
作用:延迟初始化 Bean,首次使用时创建实例。
示例
1
2
3@Lazy
@Component
public class HeavyResource { /* ... */ }
@Profile
作用:根据环境(如
dev、prod)动态加载 Bean。示例
1
2
3@Profile("dev")
@Component
public class DevDatabaseConfig { /* ... */ }
二、配置类与 Bean 定义
@Configuration
作用:标记类为配置类,替代 XML 配置文件。
示例
1
2@Configuration
public class AppConfig { /* ... */ }
@Bean
作用:在配置类中定义 Bean,常用于第三方库的实例化。
示例
1
2
3
4@Bean
public DataSource dataSource() {
return new DruidDataSource();
}
@Import
作用:导入其他配置类或组件。
示例
1
2
3@Import({DatabaseConfig.class, SecurityConfig.class})
@Configuration
public class AppConfig { /* ... */ }
@ComponentScan
作用:指定 Spring 扫描的包路径。
示例
1
2
3@ComponentScan("com.example")
@Configuration
public class AppConfig { /* ... */ }
@Conditional
作用:根据条件动态创建 Bean。
衍生注解:
@ConditionalOnClass:类路径存在时生效。@ConditionalOnMissingBean:容器中无该 Bean 时生效。
示例
1
2
3@Bean
@ConditionalOnClass(name = "com.example.ThirdPartyClass")
public ThirdPartyService thirdPartyService() { /* ... */ }
三、Spring MVC 相关
@RestController
作用:组合注解(
@Controller+@ResponseBody),用于 REST API 开发。示例
1
2@RestController
public class UserController { /* ... */ }
@RequestMapping
作用:映射 HTTP 请求到控制器方法。
示例
1
2@RequestMapping(path = "/users", method = RequestMethod.GET)
public List<User> getUsers() { /* ... */ }
@GetMapping / @PostMapping / @PutMapping / @DeleteMapping
作用:简化请求方法映射。
示例
1
2@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { /* ... */ }
@PathVariable
作用:绑定 URL 路径变量到方法参数。
示例
1
2@GetMapping("/users/{id}")
public User getUser(@PathVariable("id") Long userId) { /* ... */ }
@RequestParam
作用:绑定请求参数到方法参数,支持默认值。
示例
1
2@GetMapping("/users")
public List<User> getUsers(@RequestParam(defaultValue = "1") int page) { /* ... */ }
@RequestBody
作用:将请求体 JSON 反序列化为 Java 对象。
示例
1
2@PostMapping("/users")
public User createUser(@RequestBody User user) { /* ... */ }
@ResponseBody
作用:将方法返回值直接序列化为响应体(如 JSON)。
示例
1
2
3@ResponseBody
@GetMapping("/users")
public List<User> getUsers() { /* ... */ }
@ExceptionHandler
作用:声明方法为全局异常处理器。
示例
1
2
3
4@ExceptionHandler(UserNotFoundException.class)
public ResponseEntity<String> handleUserNotFound(UserNotFoundException ex) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(ex.getMessage());
}
四、数据访问与事务
@Transactional
作用:声明事务边界,支持方法或类级别。
示例
1
2@Transactional
public void updateUser(User user) { /* ... */ }
@Entity
作用:JPA 注解,标记类为数据库实体。
示例
1
2
3@Entity
@Table(name = "users")
public class User { /* ... */ }
@Table
作用:指定实体类对应的数据库表名。
示例
1
2
3@Table(name = "users")
@Entity
public class User { /* ... */ }
@Column
作用:定义实体类字段与数据库列的映射。
示例
1
2@Column(name = "user_name", length = 50)
private String username;
@Query
作用:在 Spring Data JPA 中定义自定义查询。
示例
1
2@Query("SELECT u FROM User u WHERE u.age > :age")
List<User> findUsersByAge(@Param("age") int age);
五、AOP 与切面编程
@Aspect
作用:声明类为切面。
示例
1
2
3@Aspect
@Component
public class LoggingAspect { /* ... */ }
@Pointcut
作用:定义切点表达式。
示例
1
2@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {}
@Before / @After / @Around
作用:定义通知类型(前置、后置、环绕)。
示例
1
2
3
4@Before("serviceMethods()")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Method called: " + joinPoint.getSignature());
}
六、Spring Boot 特有注解
@SpringBootApplication
作用:组合注解(
@Configuration+@EnableAutoConfiguration+@ComponentScan),标记主启动类。示例
1
2
3
4
5
6@SpringBootApplication
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
@EnableAutoConfiguration
作用:启用 Spring Boot 的自动配置机制。
示例
1
2
3@EnableAutoConfiguration
@Configuration
public class AppConfig { /* ... */ }
@SpringBootTest
作用:标记 Spring Boot 集成测试类。
示例
1
2@SpringBootTest
class UserServiceTest { /* ... */ }
七、其他实用注解
@Scheduled
作用:定义定时任务,支持
fixedRate和cron表达式。示例
1
2@Scheduled(cron = "0 0 12 * * ?")
public void dailyReport() { /* ... */ }
@Cacheable / @CacheEvict
作用:声明方法缓存策略。
示例
1
2@Cacheable(value = "users", key = "#id")
public User getUser(Long id) { /* ... */ }
@Valid / @Validated
作用:启用参数校验(需引入
spring-boot-starter-validation)。示例
1
2@PostMapping("/users")
public User createUser(@Valid @RequestBody User user) { /* ... */ }
@NotNull / @NotBlank / @Email
作用:参数校验注解,验证字段合法性。
示例
1
2
3
4
5
6
7public class User {
@NotBlank
private String username;
@Email
private String email;
}
