Springboot启动注解

@SpringbootApplication

这个注解是Springboot最核心的注解,用在Springboot的主类上,标识这是一个Springboot应用,用来开启Springboot的各项能力。实际上这个注解 @SpringbootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan。

@EnableAutoConfiguration

允许Springboot自动配置,帮助Springboot将所有符合条件的@Configuration配置都加载到Spring容器中。

@Configuration

@Configuration注解用于定义配置类,替换xml配置文件,被注解的类内部包含一个或多个被@Bean注解的方法。这些方法会被 AnnotationConfigApplicationContextAnnotationConfigWebApplicationContext 类进行扫描,并用于构建bean定义,初始化Spring容器。

@SpringBootConfiguration

@SpringBootConfiguration继承自@Configuration,二者功能一致,标注当前类是配置类,并将类内声明的一个或多个@Bean注解标记的方法对应的实例加载到Spring容器中。

@ComponentScan

@ComponentScan注解默认会装配标识了@Controller,@Service,@Repository,@Component注解的类到Spring容器中。扫描路径可以通过value属性或basePackages属性配置。如果不指定扫描路径则默认从声明@ComponetScan所在类的包进行扫描。

Spring Bean相关注解

@Component, @Controller, @Service, @Repository

@Component: 通用的注解,可标注任意类为Spring组件

@Controller: 对应SpringMVC控制层,主要用于接受用户请求,并调用Service层返回数据给前端

@Service: 对应Service层,主要是一些逻辑功能的实现,并调用DAO层接口

@Repository: 对应DAO层,主要用于操作数据库

@RestController

@RestController = @Controller + @ResponseBody,表示这是一个控制器Bean,并返回JSON或XML格式数据(对应前后端分离的情况)。

@Bean

@Bean明确地指示了方法产生一个bean实例,并交给Spring容器管理。

@Bean
@Scope("singleton")
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Scope

@Scope用于声明Spring Bean的作用域。

  • singletion: 单例(默认情况)
  • prototype: 每次请求创建一个新的实例
  • request: 每一次HTTP请求产生一个新的实例,该实例仅在当前HTTP request内有效
  • session: 每一个HTTP Session会产生一个新的实例,该实例仅在当前HTTP Session内有效

@Autowired

@Autowired自动注入对象到类中。

注入方式:

  • 构造器注入(推荐)

    优点:保证依赖不为空,强依赖处理(编译阶段即可发现);避免了循环依赖;提升代码可复用性

    缺点:注入参数较多时,代码臃肿不友好
  • Field注入

    优点:代码少,简洁明了

    缺点:容易出现空指针异常,Field注入允许构建对象实例的时候依赖的实例对象为空,直到调用该实例才能发现
  • Setter注入

    优点:相比构造注入,Setter注入类似于选择注入;允许在类构造完成后重新注入
# Field注入
public class UmsAdminController {
@Autowired
private UmsAdminService umsAdminService;
} # 构造器注入
public class UmsAdminController {
private UmsAdminService umsAdminService; @Autowired
public UmsAdminController(UmsAdminService umsAdminService) {
this.umsAdminService = umsAdminService;
}
} # Setter注入
public class UmsAdminController {
private UmsAdminService umsAdminService; @Autowired
public void setAdminController(UmsAdminService umsAdminService) {
this.umsAdminService = umsAdminService;
}
}

HTTP请求相关注解

HTTP的请求类型:

  • GET: 从服务器获取资源
  • POST: 在服务器创建一个新的资源
  • PUT: 更新服务器上的资源(全量更新,由客户端提供更新后的整个资源)
  • DELETE: 从服务器删除资源
  • PATCH: 更新服务器上的资源(增量更新,客户端提供更改的属性,使用较少)

@GetMapping

@GetMapping = @RequestMappig(method=RequestMethod.GET)

@PostMapping

@PostMapping= @RequestMappig(method=RequestMethod.POST)

@PutMapping

@PutMapping= @RequestMappig(method=RequestMethod.PUT)

@DeleteMapping

@DeleteMapping= @RequestMappig(method=RequestMethod.DELETE)

@PathVariable

获取路径参数。

@RequestMapping(value = "/permission/{adminId}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<List<UmsPermission>> getPermissionList(@PathVariable Long adminId) {
List<UmsPermission> permissionList = umsAdminService.getAllPermission(adminId);
return CommonResult.success(permissionList);
}

可以从请求的url中获取adminId。

@RequestParam

获取请求参数。

@RequestMapping(value = "/delete/batch", method = RequestMethod.DELETE)
@ResponseBody
public CommonResult<Object> delete(@RequestParam("ids") List<Long> ids) {
esProductService.delete(ids);
return CommonResult.success(null);
}

RequestParam会跟在url的 ? 之后。

@RequestBody

读取Request请求的body部分,并且Content-Type为application/json格式,接收到数据之后会自动将数据绑定到Java对象。

@RequestMapping(value = "/login", method = RequestMethod.POST)
@ResponseBody
public CommonResult login(@RequestBody UmsAdminLoginParam umsAdminLoginParam, BindingResult result) {
String token = umsAdminService.login(umsAdminLoginParam.getUsername(), umsAdminLoginParam.getPassword());
if (token == null) {
return CommonResult.validateFailed("用户名或密码错误");
}
Map<String, String> tokenMap = new HashMap<>();
tokenMap.put("tokenHead", tokenHead);
tokenMap.put("token", token);
return CommonResult.success(tokenMap);
} public class UmsAdminLoginParam { private String username; private String password; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
}
}

在RequestBody中发送JSON数据,后端可以把JSON数据映射到UmsAdminLoginParam类实例上。

总结:一个请求方法只能有一个@RequestBody,可以有多个@RequestParam和@PathVariable。

读取配置信息相关注解

@Value

读取简单配置信息。

# application.yml
jwt:
field: Authorization
secret: mySecret
expiration: 604800
tokenHead: Bearer
@Component
public class JwtTokenUtil { @Value("${jwt.secret}")
private String secret; @Value("${jwt.expiration}")
private Long expiration;
}

@ConfigurationProperties

@ConfigurationProperties有一个 prefix 属性,通过指定前缀来绑定配置文件中的配置信息。

使用方式:

  • 作用于类上
  • 作用于方法上:该方法需要有@Bean注解且所属类有@Configuration注解
spring:
datasource:
url: jdbc:mysql://localhost:3306/mall-learning?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: "0926"
// 作用于类上
@ConfigurationProperties(prefix = "spring.datasource")
@Component
@Getter
@Setter
public class Datasource {
private String url;
private String username;
private String password;
} // 作用于方法上
@Configuration
public class DatasourceConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public Datasource datasource() {
return new Datasource();
}
} public class ConfigurationPropertiesController {
@Autowired
private Datasource datasource;
}

这种绑定对象的方式是隐式绑定的,即配置文件中的字段除 prefix 后的名称需要与类中对应相同。

@PropertySource

@PropertySource读取指定 properties 文件。

# jwt.properties
jwt.field: Authorization
jwt.secret: mySecret
jwt.expiration: 604800
jwt.tokenHead: Bearer
@Component
@PeopertySource(name = "classpath:jwt.properties")
public class JwtTokenUtil { @Value("${jwt.secret}")
private String secret; @Value("${jwt.expiration}")
private Long expiration;
}

Springboot一些常用注解的更多相关文章

  1. SpringBoot 中常用注解

    本篇博文将介绍几种SpringBoot 中常用注解 其中,各注解的作用为: @PathVaribale 获取url中的数据 @RequestParam 获取请求参数的值 @GetMapping 组合注 ...

  2. SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍

    SpringBoot 中常用注解@PathVaribale/@RequestParam/@GetMapping介绍 本篇博文将介绍几种如何处理url中的参数的注解@PathVaribale/@Requ ...

  3. SpringBoot 中常用注解@Controller/@RestController/@RequestMapping的区别

    SpringBoot中常用注解@Controller/@RestController/@RequestMapping的区别 @Controller 处理http请求 @Controller //@Re ...

  4. SpringBoot 中常用注解@Controller/@RestController/@RequestMapping介绍

    原文 SpringBoot 中常用注解 @Controller/@RestController/@RequestMapping介绍 @Controller 处理http请求 @Controller / ...

  5. SpringBoot+Spring常用注解总结

    为什么要写这篇文章? 最近看到网上有一篇关于 SpringBoot 常用注解的文章被转载的比较多,我看了文章内容之后属实觉得质量有点低,并且有点会误导没有太多实际使用经验的人(这些人又占据了大多数). ...

  6. SpringBoot中常用注解@Controller/@RestController/@RequestMapping的区别

    @Controller 处理http请求 @Controller //@ResponseBody public class HelloController { @RequestMapping(valu ...

  7. springboot部分常用注解

    目录:[持续更新.....] spring 部分常用注解 spring boot 学习之路1(简单入门) spring boot 学习之路2(注解介绍) spring boot 学习之路3( 集成my ...

  8. springboot系列总结(二)---springboot的常用注解

    上一篇文章我们简单讲了一下@SpringBootApplication这个注解,申明让spring boot自动给程序进行必要的配置,他是一个组合注解,包含了@ComponentScan.@Confi ...

  9. SpringBoot之常用注解

    在spring boot中,摒弃了spring以往项目中大量繁琐的配置,遵循约定大于配置的原则,通过自身默认配置,极大的降低了项目搭建的复杂度.同样在spring boot中,大量注解的使用,使得代码 ...

  10. 【SpringBoot】常用注解

    @EnableAutoConfiguration 启动自动装载:使用了这个注解之后,所有引入的jar的starters都会被自动注入.这个类的设计就是为starter工作的. @RestControl ...

随机推荐

  1. Oracle学习-----基本SQL select语句

    一.基本select语句 SELECT 标识  选择那些列 FROM     标识从哪个表中选择 select * 标识 全部选择 select department_id, location_id ...

  2. css cursor: url() 使用火狐浏览器问题,鼠标没有效果

    在火狐浏览器问题使用cursor: url():鼠标没有效果,需要给使用标签添加一个height

  3. python for houdini——python在houdini中的基础应用02

    内容来源于网上视频 一.houdini python编译器 1.python shell 2.python source editor----代码可以随场景保存 构造的函数可以在外部通过hou.ses ...

  4. 【基础知识】C++算法基础(快速排序)

    快速排序: 1.执行流程(一趟快排): 2.一趟快排的结果:获得一个枢纽,在此左边皆小于此数,在此右边皆大于此数,因此可以继续使用递归获得最终的序列.

  5. FHAdmin实战获取shell

    又是一个愉快的摸鱼的一天,闲来无事去逛先知社区突然看到了一篇名为shrio权限实战绕过的文章(https://xz.aliyun.com/t/8311),这时不禁突然 回想起来之前看到过的一个微信公众 ...

  6. 微信小程序中如何设置跳转页面

    修改project.config.json内容 "cloudfunctionRoot":"cloud", //配置云开发的路径 更改app.js文件内容 App ...

  7. zip文件自动打包

    简单的文件打包 首先是问题 我们有一个文件的文件过大,我需要删除或者压缩,当然我们就是选择压缩 如果是单个我们可以直接使用压缩功能 但是多个呢? 首先获取当前目录下的文件,使用 a=`ls` | te ...

  8. elementui中对样式的修改标签

    /deep/ .el-drawer.rtl { -webkit-animation: rtl-drawer-out .3s; animation: rtl-drawer-out .3s; backgr ...

  9. 通过k8s部署服务

    一 使用docker运行fastapi程序(python封装http接口) 一 docker commit 1 下载python3的镜像 docker pull python:3.8-slim # s ...

  10. [转]常见的视频编码详解 Cinepak Codec by Radius

    AVI所采用的压缩算法并无统一的标准.也就是说,同样是以AVI为后缀的视频文件,其采用的压缩算法可能不同,需要相应的解压软件才能识别和回放该AVI文件.除了Microsoft公司之外,其他公司也推出了 ...