经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
SpringBoot常用注解详细整理
来源:jb51  时间:2021/12/8 8:38:21  对本文有异议

前言

Spring Boot常用注解整理

提示:以下是本篇文章正文内容,下面案例可供参考

一、@SpringBootApplication

此注解是Spring Boot项目的基石,创建SpringBoot项目的Application时会默认加上

  1. @SpringBootApplication
  2. public class SpringSecurityApplication{
  3. public static void main(Strings[] args){
  4. SpringApplication.run(SpringSecurityApplication,args);
  5. }
  6. }

@SpringBootApplication 看作@Configuration,@EnableAutoConfiguration,@ComponentScan 注解的集合

@EnableAutoConfiguration:启用SpringBoot的自动配置机制

@ComponentScan:扫描被@Component /@Service/@Controller注解的bean,注解默认会扫描该类所在的包下所有类

@Configuration:允许在Spring上下文中注册额外的bean或导入其他配置类

二、@Bean

Bean对象注册Spring IOC容器与使用bean对象是整个Spring框架的重点,其中@Bean就是一个将方法作为Spring Bean对象注册的一种方式

  1. package com.edu.fruit;
  2. //定义一个接口
  3. public interface Fruit<T>{
  4. //没有方法
  5. }
  6. /*
  7. *定义两个子类
  8. */
  9. package com.edu.fruit;
  10. @Configuration
  11. public class Apple implements Fruit<Integer>{//将Apple类约束为Integer类型
  12.  
  13. }
  14.  
  15. package com.edu.fruit;
  16. @Configuration
  17. public class GinSeng implements Fruit<String>{//将GinSeng 类约束为String类型
  18. }
  19. /*
  20. *业务逻辑类
  21. */
  22. package com.edu.service;
  23. @Configuration
  24. public class FruitService {
  25. @Autowired
  26. private Apple apple;
  27. @Autowired
  28. private GinSeng ginseng;
  29. //定义一个产生Bean的方法
  30. @Bean(name="getApple")
  31. public Fruit<?> getApple(){
  32. System.out.println(apple.getClass().getName().hashCode);
  33. System.out.println(ginseng.getClass().getName().hashCode);
  34. return new Apple();
  35. }
  36. }
  37. /*
  38. *测试类
  39. */
  40. @RunWith(BlockJUnit4ClassRunner.class)
  41. public class Config {
  42. public Config(){
  43. super("classpath:spring-fruit.xml");
  44. }
  45. @Test
  46. public void test(){
  47. super.getBean("getApple");//这个Bean从哪来,
  48. //从上面的@Bean下面的方法中返回的是一个Apple类实例对象
  49. }
  50. }
  51.  

三、@Autowired

@Autowired自动注入注解,最常用的一种注解将对象自动导入到类中,注解自动装配bean的类

四、Component家族

@Component:通用注解,当不知道Bean在哪一层时,可以使用@Component注解标注。
@Repository: 对应持久层—Dao层的注解,用于操作数据库相关
@Service: 对应服务层的注解,用来连接Dao层做逻辑处理
@Controller:对应Spring MVC控制层,主要接收用户请求并调用service返回给前端页面

五、@RestController

@RestController注解是@Controller注解和@ResponseBody注解的合集,用来返回Json格式给页面(带Rest格式的就是返回的Json文本)

六、@Scope

声明Spring Bean的作用域

  1. @Scope("singleton")
  2. public Person personSingleton(){
  3. return new Person();
  4. }

Spring Bean的四种作用域:singleton,prototype,request,session

七、@Configuration

一般声明配置类,使用@Component或者@Configuration

  1. @Configurantion
  2. public class AppConfig{
  3. @Bean
  4. public TransferService transferService(){
  5. return new TransferServiceImpl();
  6. }
  7. }

八、@RequsetMapping

@RequsetMapping是处理HTTP请求的最通用注解

  1. @RequestMapping("/users")
  2. public ResponseEntity<List<User>> getAllUsers(){
  3. return userRepository.findAll();
  4. }

八、@GetMapping

一般声明配置类,使用@Component或者@Configuration

九、@Configuration

@GetMapping 就等价于@RequestMapping(value="/users",method =RequsetMethod.GET)

即使用@GetMapping就相当用接收GET方法了

  1. @GetMapping("/users")
  2. public ResponseEntity<List<User>> getAllUsers(){
  3. return userRepository.findAll();
  4. }

十、@PostMapping

@PostMapping 就等价于@RequestMapping(value="/users",method =RequsetMethod.POST)

即使用@PostMapping就相当用接收Post方法了

  1. @PostMapping("/users")
  2. public ResponseEntity<List<User>> getAllUsers(){
  3. return userRepository.findAll();
  4. }

十一、@PutMapping

@PutMapping("/users/{userId}")等价于@RequestMapping(value = “/users/{userId}”,method = RequestMethod.PUT)

  1. @PutMapping("/users/{userId}")
  2. public ResponseEntity<User> updateUser(@PathVariable (value ="userId")Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest){
  3. ...
  4. }

十二、@DeleteMapping

@DeleteMapping("/users/{userId}")等价于@RequestMapping(value ="/users/{userId}",method = RequestMethod.DELETE)

  1. @DeleteMapping("/users/{userId}")
  2. public ResponseEntity deleteUser(@PathVariable(value = "userId) Long userId){
  3. ...
  4. }

十三、@ParhVariable和@RequestParam

@PathVariable 用于获取路径参数, @RequestParam用于获取查询参数

  1. @GetMapping("/users/{userId}/teachers")
  2. public List<Teacher> getUserRelatedTeachers(@PathVariable("userId") Long userId,@RequestParam(value = "type",required = false) String type){
  3. ...
  4. }

其中@PathVariable是获取请求中的{userId}值,@RequestParam则是url读取请求中type的值

比如我们url请求中/users/{123456}/teachers?type=Chinese 则我们在Controller获取到的就是userId = 123456 , type = Chinese

另在@RequestParam中 value=“参数名” required = “true/false”(true表示参数不允许不存在,false表示参数允许不存在) defaultValue="" 设置defaultValue时默认required为false。

十四、@RequestBody

用于读取Request请求的body部分,且Content-Type为application/json格式数据,接收到数据后会自动将数据绑定在Java对象上,系统会使用HttpMessageConverter来讲请求的body中的json字符串转换为Java对象

  1. @PostMapping("/sing-up")
  2. public ResponseEntity signUp(@RequsetBody @Valid UserRegisterRequest userRegisterRequest){
  3. userService.save(userRegisterRequest);
  4. return ResponseEntity.ok().build()'
  5. }

在这里插入图片描述

这就是典型的RequestBody在Post请求里进行传输数据当后端Controller接收到json格式的数据后,直接就会生成Java对象映射到UserRegisterRequest类上,这样就可以直接将userRegisterRequest对象进行存储。顺便说一下@Valid注解是用

来验证数据格式是否符合要求,如果符合要求则通过,不符合要求,提示注解中message信息

十五、读取配置信息

读取application.yml的注解

  1. wuhan2020: 武汉加油!中国加油!
  2.  
  3. my-profile:
  4. name: name
  5. email: XXXX@qq.com
  6.  
  7. library:
  8. location: dalian
  9. books:
  10. - name: name1
  11. description: description1
  12. - name: name2
  13. description: description2
  14. - name: name3
  15. description: description3
  16.  

1.@Value

使用@Value("${property}")读取简单的配置信息

  1. @Value("${wuhan2020}")
  2. String wuhan2020;

2.@ConfigurationProperties

通过@ConfigurationProperties读取配置信息并与bean绑定

  1. @Component
  2. @ConfigurationProperties(prefix = "library")
  3. class LibraryProperties{
  4. @NotEmpty
  5. private String location;
  6. private List<Book> books;
  7. @Data
  8. @ToString
  9. static class Book{
  10. String name;
  11. String description;
  12. }
  13. }
  14.  

十六、@Qualifier

当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:

  1. @Autowired
  2. @Qualifier(value = demoInfoService”)
  3. private DemoInfoService demoInfoService;

十七、@MapperScan

spring-boot支持mybatis组件的一个注解,通过此注解指定mybatis接口类的路径,即可完成对mybatis接口的扫描。

它和@mapper注解是一样的作用,不同的地方是扫描入口不一样。@mapper需要加在每一个mapper接口类上面。所以大多数情况下,都是在规划好工程目录之后,通过@MapperScan注解配置路径完成mapper接口的注入。

添加mybatis相应组建依赖之后。就可以使用该注解。

在这里插入图片描述

十八、@CrossOrigin

@CrossOrigin(origins = “”, maxAge = 1000) 这个注解主要是为了解决跨域访问的问题。这个注解可以为整个controller配置启用跨域,也可以在方法级别启用。

十九、@ControllerAdvice

@ControllerAdvice 和 @RestControllerAdvice:通常和@ExceptionHandler、@InitBinder、@ModelAttribute一起配合使用。

@ControllerAdvice 和 @ExceptionHandler 配合完成统一异常拦截处理。

@RestControllerAdvice 是 @ControllerAdvice 和 @ResponseBody的合集,可以将异常以json的格式返回数据。

如下面对数据异常返回的统一处理。

在这里插入图片描述

二十、资源导入注解

@ImportResource @Import @PropertySource 这三个注解都是用来导入自定义的一些配置文件。

@ImportResource(locations={}) 导入其他xml配置文件,需要标准在主配置类上。

导入property的配置文件 @PropertySource指定文件路径,这个相当于使用spring的标签来完成配置项的引入。

@import注解是一个可以将普通类导入到spring容器中做管理

二十一、@Transactional

通过这个注解可以声明事务,可以添加在类上或者方法上。

在spring boot中 不用再单独配置事务管理,一般情况是我们会在servcie层添加了事务注解,即可开启事务。要注意的是,事务的开启只能在public 方法上。并且主要事务切面的回滚条件。正常我们配置rollbackfor exception时 ,如果在方法

里捕获了异常就会导致事务切面配置的失效。

总结

到此这篇关于SpringBoot常用注解详细整理的文章就介绍到这了,更多相关SpringBoot常用注解内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号