Spring Boot 常用注解详解

Spring Boot 常用注解详解:让你的开发更高效

Spring Boot极大地简化了Spring应用的开发,其中注解系统是其核心特性之一。通过各种注解,开发者可以快速配置应用、定义组件、处理请求等,大大提高了开发效率。本文将详细解析Spring Boot中最常用的注解,帮助开发者更好地理解和使用这些强大的工具。

配置注解总结表

注解 用途 使用场景
@SpringBootApplication 应用入口 主类
@Configuration 配置类 Java配置
@Component 通用组件 通用Bean
@Service 服务层 业务逻辑
@Repository 数据访问层 DAO层
@Controller Web控制器 MVC控制器
@RestController REST控制器 REST API
@Autowired 依赖注入 自动装配
@Value 属性注入 配置值
@ConfigurationProperties 批量属性注入 配置类
@RequestMapping 请求映射 URL映射
@GetMapping/PostMapping等 HTTP方法映射 REST API
@PathVariable 路径参数 URL路径变量
@RequestParam 查询参数 URL查询参数
@RequestBody 请求体 JSON/XML数据
@ResponseBody 响应体 返回数据
@Valid 数据验证 参数验证
@Transactional 事务管理 数据库事务
@Profile 环境配置 多环境配置

核心配置注解

@SpringBootApplication

这是Spring Boot应用的入口注解,整合了三个核心注解的功能:

  • @SpringBootConfiguration:标识配置类
  • @EnableAutoConfiguration:启用自动配置
  • @ComponentScan:启用组件扫描
@SpringBootApplication
public class Application {
   
    public static void main(String[] args) {
   
        SpringApplication.run(Application.class, args);
    }
}

@Configuration

标识一个类作为配置类,相当于XML配置文件:

@Configuration
public class AppConfig {
   

    @Bean
    public UserService userService() {
   
        return new UserServiceImpl();
    }
}

@EnableAutoConfiguration

启用Spring Boot的自动配置机制,根据类路径中的jar包自动配置Bean:

@SpringBootApplication(exclude = {
   DataSourceAutoConfiguration.class})
public class Application {
   
    // 自动配置排除数据源配置
}

组件注册注解

@Component

通用的组件注解,标识一个类为Spring管理的组件:

@Component
public class EmailService {
   
    public void sendEmail(String to, String subject, String body) {
   
        // 发送邮件逻辑
    }
}

@Service

专门用于服务层的组件注解,语义更明确:

@Service
public class UserService {
   

    @Autowired
    private UserRepository userRepository;

    public User findById(Long id) {
   
        return userRepository.findById(id).orElse(null);
    }
}

@Repository

用于数据访问层的组件注解,自动处理数据访问异常:

@Repository
public class UserRepository {
   

    @PersistenceContext
    private EntityManager entityManager;

    public List<User> findAll() {
   
        return entityManager.createQuery("SELECT u FROM User u", User.class)
                          .getResultList();
    }
}

@Controller

标识Web层的控制器组件:

@Controller
public class HomeController {
   

    @RequestMapping("/home")
    public String home(Model model) {
   
        model.addAttribute("message", "Hello World");
        return "home";
    }
}

@RestController

组合了@Controller和@ResponseBody,用于RESTful API:

@RestController
@RequestMapping("/api/users")
public class UserController {
   

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
   
        return userService.findById(id);
    }
}

依赖注入注解

@Autowired

自动装配依赖,可以用于字段、构造器、方法:

@Service
public class UserService {
   

    @Autowired
    private UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
   
        this.userRepository = userRepository;
    }

    @Autowired
    public void setUserRepository(UserRepository userRepository) {
   
        this.userRepository = userRepository;
    }
}

@Qualifier

当存在多个相同类型的Bean时,指定具体要注入的Bean:

@Service
public class PaymentService {
   

    @Autowired
    @Qualifier("alipayService")
    private PaymentProcessor processor;
}

@Resource

JSR-250标准注解,功能类似@Autowired:

@Service
public class NotificationService {
   

    @Resource
    private EmailService emailService;
}

配置属性注解

@Value

注入配置文件中的属性值:

@Component
public class AppConfig {
   

    @Value("${app.name}")
    private String appName;

    @Value("${app.version:1.0}")  // 默认值
    private String version;

    @Value("#{systemProperties['java.home']}")
    private String javaHome;
}

@ConfigurationProperties

批量注入配置属性:

@ConfigurationProperties(prefix = "app.database")
@Component
public class DatabaseProperties {
   
    private String url;
    private String username;
    private String password;

    // getters and setters
}

@PropertySource

指定属性文件位置:

@Configuration
@PropertySource("classpath:app.properties")
public class PropertyConfig {
   
    // 配置类
}

Web请求处理注解

@RequestMapping

映射Web请求到处理方法:

@Controller
public class UserController {
   

    @RequestMapping(value = "/users", method = RequestMethod.GET)
    public String listUsers(Model model) {
   
        return "userList";
    }

    @RequestMapping(path = "/users/{id}", method = RequestMethod.PUT)
    public ResponseEntity<String> updateUser(@PathVariable Long id, @RequestBody User user) {
   
        return ResponseEntity.ok("User updated");
    }
}

@GetMapping、@PostMapping、@PutMapping、@DeleteMapping

HTTP方法特定的映射注解:

@RestController
@RequestMapping("/api/users")
public class UserController {
   

    @GetMapping
    public List<User> getAllUsers() {
   
        return userService.findAll();
    }

    @PostMapping
    public User createUser(@RequestBody User user) {
   
        return userService.save(user);
    }

    @PutMapping("/{id}")
    public User updateUser(@PathVariable Long id, @RequestBody User user) {
   
        user.setId(id);
        return userService.save(user);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteUser(@PathVariable Long id) {
   
        userService.deleteById(id);
        return ResponseEntity.noContent().build();
    }
}

@PathVariable

从URL路径中提取参数:

@GetMapping("/users/{id}/orders/{orderId}")
public Order getOrder(@PathVariable Long id, @PathVariable("orderId") Long orderId) {
   
    return orderService.findById(orderId);
}

@RequestParam

处理查询参数:

@GetMapping("/users")
public List<User> getUsers(
    @RequestParam(defaultValue = "0") int page,
    @RequestParam(defaultValue = "10") int size,
    @RequestParam(required = false) String name) {
   

    return userService.findUsers(page, size, name);
}

@RequestBody

将请求体映射到方法参数:

@PostMapping("/users")
public User createUser(@RequestBody User user) {
   
    return userService.save(user);
}

@ResponseBody

将方法返回值序列化为响应体:

@GetMapping("/api/version")
@ResponseBody
public Map<String, String> getVersion() {
   
    Map<String, String> response = new HashMap<>();
    response.put("version", "1.0.0");
    return response;
}

数据验证注解

JSR-303验证注解

用于数据验证:

public class User {
   

    @NotNull(message = "用户名不能为空")
    @Size(min = 3, max = 20, message = "用户名长度必须在3-20之间")
    private String username;

    @Email(message = "邮箱格式不正确")
    private String email;

    @Min(value = 18, message = "年龄不能小于18岁")
    private int age;
}

在控制器中启用验证:

@PostMapping("/users")
public ResponseEntity<String> createUser(@Valid @RequestBody User user, BindingResult result) {
   
    if (result.hasErrors()) {
   
        return ResponseEntity.badRequest().body("数据验证失败");
    }
    userService.save(user);
    return ResponseEntity.ok("用户创建成功");
}

AOP相关注解

@Aspect

标识切面类:

@Aspect
@Component
public class LoggingAspect {
   

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
   
        System.out.println("Method: " + joinPoint.getSignature().getName() + " is called");
    }
}

@Pointcut

定义切点表达式:

@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceLayer() {
   }

@Before("serviceLayer()")
public void beforeService(JoinPoint joinPoint) {
   
    // 前置通知逻辑
}

事务管理注解

@Transactional

声明事务:

@Service
public class UserService {
   

    @Transactional
    public User saveUser(User user) {
   
        userRepository.save(user);
        // 如果这里抛出异常,整个事务会回滚
        return user;
    }

    @Transactional(readOnly = true)
    public List<User> findAllUsers() {
   
        return userRepository.findAll();
    }
}

条件注解

@Conditional

根据条件决定是否创建Bean:

@Conditional(OnLinuxCondition.class)
@Component
public class LinuxService {
   
    // 只在Linux系统上创建
}

@Profile

根据激活的profile决定是否创建Bean:

@Profile("dev")
@Component
public class DevDatabaseConfig {
   
    // 开发环境数据库配置
}

@Profile("prod")
@Component
public class ProdDatabaseConfig {
   
    // 生产环境数据库配置
}

测试相关注解

@SpringBootTest

用于集成测试:

@SpringBootTest
class UserServiceTest {
   

    @Autowired
    private UserService userService;

    @Test
    void testCreateUser() {
   
        User user = new User();
        user.setUsername("test");
        User savedUser = userService.save(user);
        assertThat(savedUser.getId()).isNotNull();
    }
}

@MockBean

创建Mock对象:

@SpringBootTest
class UserControllerTest {
   

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private UserService userService;

    @Test
    void testGetUser() throws Exception {
   
        when(userService.findById(1L)).thenReturn(new User("test"));

        mockMvc.perform(get("/api/users/1"))
               .andExpect(status().isOk())
               .andExpect(jsonPath("$.username").value("test"));
    }
}

配置注解总结表

注解 用途 使用场景
@SpringBootApplication 应用入口 主类
@Configuration 配置类 Java配置
@Component 通用组件 通用Bean
@Service 服务层 业务逻辑
@Repository 数据访问层 DAO层
@Controller Web控制器 MVC控制器
@RestController REST控制器 REST API
@Autowired 依赖注入 自动装配
@Value 属性注入 配置值
@ConfigurationProperties 批量属性注入 配置类
@RequestMapping 请求映射 URL映射
@GetMapping/PostMapping等 HTTP方法映射 REST API
@PathVariable 路径参数 URL路径变量
@RequestParam 查询参数 URL查询参数
@RequestBody 请求体 JSON/XML数据
@ResponseBody 响应体 返回数据
@Valid 数据验证 参数验证
@Transactional 事务管理 数据库事务
@Profile 环境配置 多环境配置

最佳实践

  1. 合理使用注解:选择语义明确的注解,如@Service用于服务层
  2. 配置外化:使用@ConfigurationProperties管理配置
  3. 数据验证:在API层使用验证注解确保数据质量
  4. 事务管理:在适当的方法上使用@Transactional
  5. 条件配置:使用@Conditional和@Profile实现环境差异化配置

Spring Boot的注解系统为开发者提供了强大的功能和便利性,掌握这些常用注解能够显著提高开发效率和代码质量。通过合理使用这些注解,可以构建出结构清晰、易于维护的Spring Boot应用。

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/pnotes/318984.html

(0)
上一篇 1天前
下一篇 5小时前

相关推荐

发表回复

登录后才能评论