锋盈数科-知识库 Logo
首页
软件开发
计算机基础
Hello Halo
新手必读
关于本知识库
登录 →
锋盈数科-知识库 Logo
首页 软件开发 计算机基础 Hello Halo 新手必读 关于本知识库
登录
  1. 首页
  2. 软件开发
  3. Spring Boot注解汇总(详细)

Spring Boot注解汇总(详细)

0
  • 软件开发
  • 发布于 2024-08-17
  • 0 次阅读
黄健
黄健

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

Spring Boot 提供了许多注解,这些注解使得开发者能够快速地配置和集成 Spring 应用程序。以下是一些常用的 Spring Boot 注解:

1、@SpringBootApplication

        这是一个组合注解,包含了 @SpringBootConfiguration、@EnableAutoConfiguration 和 @ComponentScan。包含三者的功能。

举例:

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

源代码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
    excludeFilters = {@Filter(
    type = FilterType.CUSTOM,
    classes = {TypeExcludeFilter.class}
), @Filter(
    type = FilterType.CUSTOM,
    classes = {AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
    //省略其他代码,详情参考具体源码
}

2、@SpringBootConfiguration

        这个注解包含了 @Configuration,@Configuration 里面又包含了一个 @Component 注解,也就是说,这个注解标注在哪个类上,就表示当前这个类是一个配置类,而配置类也是 spring 容器中的组件。

源代码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {
}

3、@EnableAutoConfiguration

        开启自动配置的功能。

源代码:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import({AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    //省略其他代码,详情参考具体源码
}

4、@ComponentScan

        启用组件扫描(可以设置扫描路径),允许 Spring Boot 发现和注册控制器、服务等组件。

源代码:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {
    //省略其他代码,详情参考具体源码
}

5、@RestController

        这是一个组合注解,等同于 @Controller 和 @ResponseBody。用于创建返回 JSON、XML 等内容作为响应主体的 REST 控制器。用于将 JSON 等内容数据返回,数据不走视图处理器,直接写入到输入流中。

举例(在访问地址输入 “/hello” 后生成一个临时页面输出 "Hello, SpringBoot"):

@RestController
public class DemoController {
    @RequestMapping("/hello")
    public String hello(){
        return "Hello, SpringBoot";
    }
}

6、@Controller

        用于标记在一个类上,使用它标记的类就是一个 SpringMVC Controller 对象。用于将返回的数据返回到一个页面,数据走视图处理器。

举例(在访问地址输入 “/show” 后,通过 ModelMap 向 index 页面传输 msg,在页面可以通过 msg 获取对应的值):

@Controller
public class Demo2Controller {
    @RequestMapping("/show")
    public String show(ModelMap map){
        map.put("msg","这是来自控制器的一条信息");
        return "index";
    }
}

7、@ResponseBody

         将 Controller 的方法返回的对象,通过适当的转换器转换为指定的格式之后,写入到 response 对象的 body 区,通常用来返回 JSON 数据或者是 XML 数据。一般作用在方法上。

举例(不会跳转到 success 页面,而是直接显示 “success” 字符串):

@Controller
public class Demo2Controller {
    @ResponseBody
    @RequestMapping("/test")
    public String test(){
        return "success";
    }
}

8、@RequestMapping

        处理请求访问地址映射的注解,可用于映射一个请求或一个方法,可以用在类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。用于方法上,表示在类的父路径下追加方法上注解中的地址将会访问到该方法。类上可以不用。

举例(要使用 show 方法,必须访问地址 “/demo2/show”, 类上的映射地址和方法上的映射地址都必须写上):

@Controller
@RequestMapping("/Demo2")
public class Demo2Controller {
    @RequestMapping("/show")
    public String show(ModelMap map){
        map.put("msg","这是来自控制器的一条信息");
        return "index";
    }
}

9、@GetMapping、@PostMapping、@PutMapping、@DeleteMapping

        功能和 @RequestMapping 类似,用于处理特别的请求,分别用于处理 GET、POST、PUT、DELETE 请求。

举例:

@RestController
public class Demo3Controller {
    @GetMapping("/get")
    public String get(){
        return "get 请求数据信息";
    }
    @PostMapping("/post")
    public String post(){
        return "post 请求数据信息";
    }
    @PutMapping("/put")
    public String put(){
        return "put 请求数据信息";
    }
    @DeleteMapping("/delete")
    public String delete(){
        return "delete 请求数据信息";
    }
}

10、@Configuration

        用于标注配置类,替代 XML 配置。

举例(标注 DemoConfig 为配置类):

@Configuration
public class DemoConfig {
    @Bean
    public User test(){
        return new User();
    }
}

11、@Bean

        用于将外部配置的值注入到 Bean 中。

举例(test 方法会创建 User 这样的 Bean):

@Configuration
public class DemoConfig {
    @Bean
    public User test(){
        return new User();
    }
}

12、@Component

        标注 Spring 管理的 Bean,使用 @Component 注解在一个类上,表示将此类标记为 Spring 容器中的一个 Bean。基于 @Component 注解的有以下几个:

        @Controller: controller 控制器层
@Service : service 服务层(或业务逻辑层)
@Repository : dao 持久层(或数据访问层)
举例:

@Component
public class User {
}

13、@Service

        是 Spring Framework 中的一个注解,用于标识一个类为服务层(或业务逻辑层)组件。

举例:

@Service
public class UserService {
}

14、@Repository

        是 Spring Framework 中的一个注解,用于标识一个类为数据访问层 (DAO 层) 组件。

@Repository
public class UserDao {
}

15、@Value

        用于将外部配置的值注入到 Bean 中,一般将配置文件中的变量的值注入到当前类的成员变量中,也可以直接设置值。

举例(假设配置文件中已设置 user.name):

public class User {
    @Value("${user.name}")
    private String name;
    @Value("xxx@qq.com")
    private String email;
}

16、@ConfigurationProperties

        用于绑定和验证来自外部源的配置属性。一般作用在类上。

举例(假设配置文件中已设置 user.name 和 user.email):

@ConfigurationProperties(prefix = "user")
public class User {
    private String name;
    private String email;
    public void setName(String name) {
        this.name = name;
    }
    public void setEmail(String email) {
        this.email = email;
    }
}

17、@RequestParam

        用于将请求参数绑定到控制器的处理方法的参数上。

举例(从前端页面传入两个参数 username 和 password,可以使用 @RequestParam 将前端的 username 参数和后端方法的 name 参数进行映射对应传参,password 和 pwd 同理):

@RequestMapping("/login")
public String login(@RequestParam("username") String name, @RequestParam("password")String pwd){
    if(name.equals("admin")&&pwd.equals("123456")){
        return "index";  
    }else{
        return "error";
    }
}

18、@PathVariable

        用于将 URI 模板变量映射到控制器处理方法的参数上。

举例(假设在 URL 输入:http://localhost:8080/showName/zhangsan, 可以获取到输入的 zhangsan):

@RequestMapping("/showName/{name}")
public String showName(@PathVariable("name") String name){
    return name;
}

19、@EnableCaching

        开启基于注解的缓存,一般用在主启动类或者配置类上。

举例:

@SpringBootApplication
@EnableCaching
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

20、@Cacheable

        作用在方法或者类上。在方法执行之前,会先根据 key 查看缓存中是否有对应缓存数据,如果有,直接从缓存中取数据,不运行方法;如果没有,执行方法,并将方法的返回值存入缓存。

举例:

@Service
public class UserService {
    @Autowired
    UserDao userDao;
    @Cacheable(value = "user",key = "#id")
    public User getUserById(int id){
        return userDao.getUserById(id);
    }
}

21、@CachePut

        作用在类或者方法上,在方法被调用的同时使得返回值被存入缓存。

举例:

@CachePut(value = "user",key = "#id")
public User updateUserById(int id){
    return userDao.getUserById(id);
}

22、@CacheEvict

        作用在类或者方法上,在方法执行后,删除 key 对应的缓存。

举例:

@CacheEvict(value = "user",key="#id")
public void deleteUserById(int id){
    userDao.deleteUserById(id);
}

23、@CacheConfig

        主要用于统筹管理类中所有的使用 @Cachable,@CachePut,@CacheEvict 标注的方法中的公告属性,例如缓存名等。

举例:

@Caching(

        cacheable = {

                @Cacheable(value = "emp",key = "#lastName")

        },

        put = {

                @CachePut(value = "emp",key = "#result.id"),

                @CachePut(value = "emp",key = "#result.email"),

        }

)

24、@EnableScheduling

        是 Spring Framework 提供的一个注解,用于启用定时任务功能。一般标注在启动类上。

举例:

@SpringBootApplication
@EnableScheduling
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

25、@Scheduled

        标注在方法上,创建一个定时任务方法,可以指定执行的时间间隔或时间点

举例:

@Scheduled(fixedRate = 5000)  // 每隔 5 秒执行一次

    public void performTask() {

        // 执行定时任务的逻辑

        System.out.println("定时任务执行中...");

 }

26、@Transactional

        @Transactional 可以作用在接口、类、类方法,用于声明事务
作用于类:当把 @Transactional 注解放在类上时,表示所有该类的 public 方法都配置相同的事务属性信息。
作用于方法:当类配置了 @Transactional,方法也配置了 @Transactional,方法的事务会覆盖类的事务配置信息。
作用于接口:不推荐这种使用方法,因为一旦标注在 Interface 上并且配置了 Spring AOP 使用 CGLib 动态代理,将会导致 @Transactional 注解失效。

举例:

@Transactional
public void transferAccount(int id,int account){
    //省略代码
}

27、@Profiles

        作用是指定类或方法在特定的 Profile 环境生效,任何@Component或@Configuration注解的类都可以使用@Profile注解。

举例(假设已经配置了 prod 环境):
@Configuration
@Profile("prod")
public class ProdConfig {
@Bean
public User changeData {
// 省略代码
}

}

以上是常用的 Spring Boot 注解。

标签: #Spring Boot 173 #软件开发 1171 #JAVA 991
相关文章

万字:支付“核心系统”详解 2024-11-02 15:33

专栏作者:隐墨星辰 \| 主编:陈天宇宙 这篇文章也尝试化繁为简,探寻支付系统的本质,讲清楚在线支付系统最核心的一些概念和设计理念。 虽然支付行业已经过了风头最劲的时光,但跨境支付仍然在蓬勃发展,每年依然有很多新人进入这个行业,这篇文章尝试为这些刚入行的新人提供一点帮助。 文章只介绍一些支付行业十几

资深支付架构师视角:实战从问题定义到代码落地的完整套路 2024-11-02 15:33

前言 今天从一个实际案例入手,介绍站在架构师的角度,如何识别并定义问题,提炼需求,技术方案选型,再到详细设计,最后利用AI的能力协助写出核心的代码,验证与调优。 解决问题存在一定的模式,也可以称之为框架,总结出自己的思考和解题框架,以后再碰到同类型的问题就可以如庖丁解牛一样容易。 很多年前,我写代码

Spring 实现 3 种异步接口 2024-10-18 09:07

大家好,我是苏三~ 如何处理比较耗时的接口? 这题我熟,直接上异步接口,使用 Callable、WebAsyncTask 和 DeferredResult、CompletableFuture等均可实现。 但这些方法有局限性,处理结果仅返回单个值。在某些场景下,如果需要接口异步处理的同时,还持续不断地

重学SpringBoot3-集成Redis(五)之布隆过滤器 2024-10-08 11:24

更多SpringBoot3内容请关注我的专栏:《SpringBoot3》 期待您的点赞👍收藏⭐评论✍ 重学SpringBoot3-集成Redis(五)之布隆过滤器 1. 什么是布隆过滤器? * 基本概念 适用场景 2. 使用 Redis 实现布隆过滤器 * 项目依赖 Redis 配置

设计模式第16讲——迭代器模式(Iterator) 2024-10-08 11:24

一、什么是迭代器模式 迭代器模式是一种行为型设计模式,它提供了一种统一的方式来访问集合对象中的元素,而不是暴露集合内部的表示方式。简单地说,就是将遍历集合的责任封装到一个单独的对象中,我们可以按照特定的方式访问集合中的元素。 二、角色组成 抽象迭代器(Iterator):定义了遍历聚合对象所需的方法

vue2路由和vue3路由区别及原理 2024-10-08 11:24

一、Vue2 与 Vue3 路由的区别 1. 创建路由实例方式的不同 Vue 2 中,通过 Vue.use() 注册路由插件,并通过 new VueRouter() 来创建路由实例。 import Vue from 'vue';import VueRouter from 'vue-router';i

目录

IT 外包服务商

  • 意见投递
  • zyf6619

软件开发应用

主菜单

  • 首页
  • 软件开发
  • 计算机基础
  • Hello Halo
  • 新手必读
  • 关于本知识库
Copyright © 2024 your company All Rights Reserved. Powered by Halo.