当前位置: 首页 > news >正文

Spring Boot(7)Spring Boot 注解全解析:深入理解与应用

搞个引言

在现代 Java 开发中,Spring Boot 凭借其便捷性和高效性成为了众多开发者的首选框架。而注解作为 Spring Boot 的核心特性之一,极大地简化了开发过程,提高了代码的可读性和可维护性。本文将深入探讨 Spring Boot 中几种重要的注解,帮助你全面理解它们的作用和使用场景。

一、Spring Boot 启动注解

1.1 @SpringBootApplication

@SpringBootApplication 是 Spring Boot 应用中最常用的注解之一,它是一个组合注解,包含了 @SpringBootConfiguration@EnableAutoConfiguration@ComponentScan

1.1.1 @SpringBootConfiguration

@SpringBootConfiguration 继承自 @Configuration,用于标记当前类是一个 Spring 的配置类。配置类就像是一个 XML 配置文件的 Java 版本,它可以包含多个 Bean 的定义。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

    @Bean
    public MyService myService() {
        return new MyService();
    }
}

class MyService {
    public void doSomething() {
        System.out.println("Doing something...");
    }
}
1.1.2 @EnableAutoConfiguration

@EnableAutoConfiguration 是 Spring Boot 自动配置的核心注解。它会根据类路径下的依赖和配置,自动为应用配置合适的 Bean。例如,如果类路径下存在 Spring Data JPA 的依赖,Spring Boot 会自动配置数据源和 JPA 相关的 Bean。

1.1.3 @ComponentScan

@ComponentScan 用于指定 Spring 扫描组件的包路径。Spring 会自动扫描指定包及其子包下的所有带有 @Component@Service@Repository@Controller 等注解的类,并将它们注册为 Spring Bean。

1.2 @Enable* 系列注解

除了 @EnableAutoConfiguration,Spring Boot 还有许多以 @Enable 开头的注解,用于启用特定的功能。

1.2.1 @EnableScheduling

@EnableScheduling 用于启用 Spring 的定时任务功能。在配置类上添加该注解后,就可以使用 @Scheduled 注解来定义定时任务。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

@SpringBootApplication
@EnableScheduling
public class ScheduledTaskApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScheduledTaskApplication.class, args);
    }

    @Scheduled(fixedRate = 5000) // 每 5 秒执行一次
    public void performTask() {
        System.out.println("Task is running...");
    }
}
1.2.2 @EnableAsync

@EnableAsync 用于启用 Spring 的异步方法执行功能。在配置类上添加该注解后,就可以使用 @Async 注解来标记异步方法。

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@SpringBootApplication
@EnableAsync
public class AsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }
}

@Service
class MyAsyncService {

    @Async
    public void asyncMethod() {
        try {
            Thread.sleep(3000);
            System.out.println("Async method completed.");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

二、组件扫描与 Bean 定义注解

2.1 @Component、@Service、@Repository 和 @Controller

这些注解都用于标记一个类为 Spring 的组件,它们的区别主要在于语义上的不同。

2.1.1 @Component

@Component 是一个通用的组件注解,用于标记任何 Spring 管理的组件。当一个类没有明确的角色时,可以使用 @Component 注解。

import org.springframework.stereotype.Component;

@Component
public class MyComponent {
    public void doSomething() {
        System.out.println("MyComponent is doing something.");
    }
}
2.1.2 @Service

@Service 用于标记业务逻辑层的服务类。它是 @Component 的一个特殊化注解,主要用于表示服务层的组件。

import org.springframework.stereotype.Service;

@Service
public class UserService {
    public void saveUser() {
        System.out.println("Saving user...");
    }
}
2.1.3 @Repository

@Repository 用于标记数据访问层的类,通常用于与数据库交互的 DAO(Data Access Object)类。它也是 @Component 的一个特殊化注解,并且 Spring 会自动处理 @Repository 注解类抛出的异常。

import org.springframework.stereotype.Repository;

@Repository
public class UserRepository {
    public void saveUserToDatabase() {
        System.out.println("Saving user to database...");
    }
}
2.1.4 @Controller

@Controller 用于标记控制器类,负责处理 HTTP 请求。它也是 @Component 的一个特殊化注解,通常与 Spring MVC 框架一起使用。

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloController {

    @GetMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello, Spring Boot!";
    }
}

2.2 @Configuration 和 @Bean

2.2.1 @Configuration

@Configuration 用于标记一个类为配置类,它可以包含多个 @Bean 注解的方法,用于定义 Spring Bean。

import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Bean;

@Configuration
public class AppConfig {

    @Bean
    public MyBean myBean() {
        return new MyBean();
    }
}

class MyBean {
    public void doSomething() {
        System.out.println("MyBean is doing something.");
    }
}
2.2.2 @Bean

@Bean 用于在配置类中定义一个 Bean。它可以将一个方法的返回值注册为 Spring 容器中的 Bean。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AnotherConfig {

    @Bean
    public String myStringBean() {
        return "This is a string bean.";
    }
}

三、依赖注入注解

3.1 @Autowired

@Autowired 是 Spring 中最常用的依赖注入注解,它可以自动将 Spring 容器中的 Bean 注入到需要的地方。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    private final UserRepository userRepository;

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

    public void saveUser() {
        userRepository.saveUserToDatabase();
    }
}

3.2 @Qualifier

当一个接口有多个实现类时,使用 @Autowired 可能会导致歧义。这时可以使用 @Qualifier 注解来指定具体要注入的 Bean。

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

interface MessageService {
    void sendMessage();
}

@Service("emailService")
class EmailService implements MessageService {
    @Override
    public void sendMessage() {
        System.out.println("Sending email...");
    }
}

@Service("smsService")
class SmsService implements MessageService {
    @Override
    public void sendMessage() {
        System.out.println("Sending SMS...");
    }
}

@Service
public class MessageSenderService {

    private final MessageService messageService;

    @Autowired
    public MessageSenderService(@Qualifier("emailService") MessageService messageService) {
        this.messageService = messageService;
    }

    public void send() {
        messageService.sendMessage();
    }
}

3.3 @Resource

@Resource 是 Java 标准的依赖注入注解,它可以根据名称或类型进行注入。默认情况下,它会根据名称进行注入。

import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class ResourceInjectionService {

    @Resource(name = "emailService")
    private MessageService messageService;

    public void sendMessage() {
        messageService.sendMessage();
    }
}

四、Spring MVC 注解

4.1 @RestController

@RestController@Controller@ResponseBody 的组合注解,用于标记一个类为 RESTful 风格的控制器。它会自动将控制器方法的返回值转换为 JSON 或 XML 等格式返回给客户端。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RestfulController {

    @GetMapping("/data")
    public String getData() {
        return "{\"name\": \"John\", \"age\": 30}";
    }
}

4.2 @RequestMapping、@GetMapping、@PostMapping 等

4.2.1 @RequestMapping

@RequestMapping 是一个通用的请求映射注解,用于将 HTTP 请求映射到控制器的方法上。它可以指定请求的路径、请求方法(如 GET、POST 等)、请求参数等。

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class RequestMappingController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String hello() {
        return "Hello, RequestMapping!";
    }
}
4.2.2 @GetMapping、@PostMapping 等

@GetMapping@PostMapping@PutMapping@DeleteMapping 等是 @RequestMapping 的简化注解,分别对应 HTTP 的 GET、POST、PUT、DELETE 请求方法。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class SimplifiedMappingController {

    @GetMapping("/get")
    public String get() {
        return "This is a GET request.";
    }

    @PostMapping("/post")
    public String post() {
        return "This is a POST request.";
    }
}

4.3 @RequestBody 和 @RequestParam

4.3.1 @RequestBody

@RequestBody 用于将 HTTP 请求的 body 部分绑定到方法的参数上。通常用于处理 JSON 或 XML 格式的请求数据。

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

class User {
    private String name;
    private int age;

    // Getters and setters
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

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

    @PostMapping
    public String createUser(@RequestBody User user) {
        return "User created: " + user.getName() + ", " + user.getAge();
    }
}
4.3.2 @RequestParam

@RequestParam 用于从 HTTP 请求的参数中获取值,并绑定到方法的参数上。

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/search")
public class SearchController {

    @GetMapping
    public String search(@RequestParam String keyword) {
        return "Searching for: " + keyword;
    }
}

五、数据访问注解

5.1 @Entity 和 @Table

5.1.1 @Entity

@Entity 用于标记一个类为 JPA 实体类,该类对应数据库中的一张表。

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private double price;

    // Getters and setters
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }
}
5.1.2 @Table

@Table 用于指定实体类对应的数据库表名。如果不指定,默认表名与实体类名相同。

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "products")
public class Product {
    // 同上
}

5.2 @Column 和 @Id

5.2.1 @Column

@Column 用于指定实体类的属性对应数据库表的列名。如果不指定,默认列名与属性名相同。

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
@Table(name = "products")
public class Product {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "product_name")
    private String name;

    private double price;

    // Getters and setters
}
5.2.2 @Id

@Id 用于标记实体类的属性为主键。

5.3 @Repository

在数据访问层,@Repository 注解用于标记 DAO 类,并且 Spring 会自动处理该类抛出的异常。

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.Product;

@Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
}

六、AOP 注解

6.1 @Aspect

@Aspect 用于标记一个类为切面类,该类可以包含多个通知方法。

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.demo.service.*.*(..))")
    public void beforeAdvice() {
        System.out.println("Before method execution...");
    }
}

6.2 @Before、@After、@Around 等

6.2.1 @Before

@Before 是一个前置通知注解,用于在目标方法执行之前执行通知方法。

6.2.2 @After

@After 是一个后置通知注解,用于在目标方法执行之后执行通知方法,无论目标方法是否抛出异常。

6.2.3 @Around

@Around 是一个环绕通知注解,它可以在目标方法执行前后都进行增强处理,并且可以控制目标方法是否执行。

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class AroundAspect {

    @Around("execution(* com.example.demo.service.*.*(..))")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Before method execution...");
        Object result = joinPoint.proceed();
        System.out.println("After method execution...");
        return result;
    }
}

七、总结

Spring Boot 中的注解为开发者提供了强大而便捷的功能呀,通过合理使用这些注解,可以大大简化开发过程,提高代码的质量和可维护性。你学费啦吗!

✍结尾

🀙🀚🀛🀜🀝🀞🀟🀠🀡🀐🀑🀒🀓🀔🀕🀖🀘🀗🀏🀎🀍🀌🀋🀊🀉🀈🀇🀆🀅🀃🀂🀁🀀🀄︎🀢🀣🀥🀤🀦🀧🀨🀩🀪

📘 妹妹听后点了点头,脸上露出了满意的笑容。她轻声说道:“原来如此,谢谢你,鸽鸽。看来我不仅要多读书,还要多动手实践,提升自己才行。”

看着她那充满求知欲的眼神,我不禁感叹,学习之路虽然充满挑战,但有这样一位美丽聪慧的伙伴相伴,一切都变得格外有意义。快去和妹妹一起实践一下吧!

求赞图

📘相关阅读⚡⚡

笔者 綦枫Maple 的其他作品,欢迎点击查阅哦~:
📚Jmeter性能测试大全:Jmeter性能测试大全系列教程!持续更新中!
📚UI自动化测试系列: Selenium+Java自动化测试系列教程❤
📚移动端自动化测试系列:Appium自动化测试系列教程
📚Postman系列:Postman高级使用技巧系列


👨‍🎓作者:綦枫Maple
🚀博客:CSDN、掘金等
🚀CSDN技术社区:https://bbs.csdn.net/forums/testbean
🚀网易云音乐:https://y.music.163.com/m/user?id=316706413
🚫特别声明:原创不易,转载请附上原文出处链接和本文声明,谢谢配合。
🙏版权声明:文章里可能部分文字或者图片来源于互联网或者百度百科,如有侵权请联系处理。
🀐其他:若有兴趣,可以加文章结尾的Q群,一起探讨学习哦~

相关文章:

  • 【数据可视化-17】基于pyecharts的印度犯罪数据可视化分析
  • 信息收集-Web应用搭建架构指纹识别WAF判断蜜罐排除开发框架组件应用
  • JavaScript 中定位 DOM 元素的 15 种方法详解(含高频使用场景案例)
  • ES 命令行查询
  • 从算法到落地:DeepSeek如何突破AI工具的同质化竞争困局
  • synchronized关键字
  • MG协议转换器:破解暖通设备通讯壁垒的智能钥匙
  • 推荐的、好用的线性稳压器
  • 微信小程序实战项目001:NBA球队太阳队简介
  • 第R6周:LSTM实现糖尿病探索与预测
  • 19.4.9 数据库方式操作Excel
  • LeetCode 热门100题-无重复字符的最长子串
  • 用大模型学大模型03-数学基础 概率论 随机变量 概率分布
  • 如何在OCP部署Java应用程序
  • 在计算机视觉任务中,Transformer架构与CNN各自的优势和劣势有哪些?
  • 【Leetcode 每日一题】1552. 两球之间的磁力
  • 工业光源中的偏光板
  • ArrayList、LinkedList、Vector
  • CSS 实现下拉菜单效果实例解析
  • 什么是偏光环形光源
  • 商城建设开发/seo网站优化公司
  • 为什么自己做不出一个好网站/关键词排名seo
  • 在线做春节网站/淘宝关键词优化推广排名
  • 淘宝客网站一定要备案吗/南宁网站seo优化公司
  • 微网站的案例/百度投流
  • 做网站用什么系统好/广州代运营公司有哪些