SpringBoot常用注解
1. @SpringBootApplication
springBoot的基石,启动类
@Configuration 应许spring注册额外的bean或者导入其他配置类
@EnableAutoConfiguration 启用 SpringBoot 的自动配置机制
@ComponentScan 自动扫描启动类所在的路径之下的bean
2. @Autowired @Resource
@Autowired
根据Type注入,不匹配name 需要结合@Qualifier匹配name使用
- 导入Bean
- 指定初始化的构造方法
@Resource
默认byName注入,多个时匹配Type
3. @Component,@Repository,@Service, @Controller,@Configuration
标识不同类型的bean
@Component
通用
@Controller
控制器层
@Service
服务层
@Repository
数据层
@Configuration
配置类
4. @RestController 返回Json/Xml形式数据
@Controller MVC控制器bean 返回一个页面,结合EL表达式渲染页面
@ResponsBody 通过转换器转换为指定的格式之后写入到Response对象的 body中
5. @Scope
声明Bean的作用域
- singleton : 唯一实例, 默认
- prototype : 每次请求都会创建一个新的实例
- request : 每一次 HTTP 请求产生一个新的 bean,当次请求有效
- session : 每一次服务启动会产生一个新的 bean,当次服务期内有效
6. @Import,@ImportResource,@Bean
@Import
:用来导入其他配置类。
@ImportResource
: 用来加载xml配置文件。
@Bean
:@Bean标注方法等价于XML中配置的bean
7. @RequestMapping、@GetMapping、@Postmapping、@PutMapping、@DeleteMapping、@PatchMapping
@GetMapping("users") 等价于 查询 @RequestMapping(value="/users",method=RequestMethod.GET) @PostMapping("users") 等价于 增加@RequestMapping(value="/users",method=RequestMethod.POST) @PutMapping("/users/{userId}") 等价于 整体更新@RequestMapping(value="/users/{userId}",method=RequestMethod.PUT) @DeleteMapping("/users/{userId}")等价于 删除@RequestMapping(value="/users/{userId}",method=RequestMethod.DELETE) @PatchMapping("/update") 局部更新 public int updateById(MyStudent myStudent) { return myStudentMapper.updateByPrimaryKey(myStudent); }
8. @PathVariable、 @RequestParam、@RequestBody
只有一个@RequestBody
,但是可以有多个@RequestParam
和@PathVariable
前后端传值的方式:
@PathVariable
用于获取路径参数 {}中的参数@RequestParam
用于获取查询参数。 type=web 键值对的形式@RequestBody
request请求(POST,PUT,DELETE,GET)的body部分
Content-Type 为 application/json,系统会使用HttpMessageConverter
或者自定义的HttpMessageConverter
将请求的 body 中的 json 字符串转换为 java 对象。
HttpServletRequest
对象- ajax
$.ajax({ type: "POST", url: "form/version/versionParam", contentType: "application/json; charset=utf-8", data: JSON.stringify(idList), async: false, success: function (message) { }, error: function (meg) { alert("出错了!"); } });
- jsp表单提交
<form action="demo.do" method="post"> ⽤户名:<br> <input type="text" name="username"><br> 密码:<br> <input type="password" name="password" ><br><br> <input type="submit" value="提交"> </form>
9. @Value
、@ConfigurationProperties
、@PropertySource
wuhan2020: 2020年初武汉爆发了新型冠状病毒,疫情严重 library: location: 湖北武汉加油中国加油 books: - name: 天才基本法 description: 恰是父亲当年为她放弃的那所。 - name: 时间的秩序 description: 为什么我们记得过去,而非未来? - name: 了不起的我 description: 如何养成一个新习惯?
使用 @Value("${property}")
读取比较简单的配置信息
@Value("${wuhan2020}") String wuhan2020;
通过@ConfigurationProperties
读取配置信息并与 bean 绑定
如下如果没有加Component注解需要在使用的地方加上
@EnableConfigurationProperties(LibraryProperties.class)
注册bean
@Component //这里 @ConfigurationProperties(prefix = "library") class LibraryProperties { @NotEmpty private String location; private List<Book> books; @Setter @Getter @ToString static class Book { String name; String description; } 省略getter/setter ...... }
@PropertySource
读取指定 properties 文件
@Component @PropertySource("classpath:website.properties") class WebSite { @Value("${url}") private String url; 省略getter/setter ...... }
10. @CrossOrigin
同源是指,域名,协议,端口均相同
允许跨域请求
- origins: 允许可访问的域列表
- maxAge:准备响应前的缓存持续的最大时间(以秒为单位)。
11. 参数校验相关(Hibernate Validator)
推荐使用 JSR 注解,即javax.validation.constraints
校验数据可以在任何一个地方,不止接口层
常用的字段验证的注解
@NotEmpty
被注释的字符串的不能为 null 也不能为空@NotBlank
被注释的字符串非 null,并且必须包含一个非空白字符@Null
被注释的元素必须为 null@NotNull
被注释的元素必须不为 null@AssertTrue
被注释的元素必须为 true@AssertFalse
被注释的元素必须为 false@Pattern(regex=,flag=)
被注释的元素必须符合指定的正则表达式@Email
被注释的元素必须是 Email 格式。@Min(value)
被注释的元素必须是一个数字,其值必须大于等于指定的最小值@Max(value)
被注释的元素必须是一个数字,其值必须小于等于指定的最大值@DecimalMin(value)
被注释的元素必须是一个数字,其值必须大于等于指定的最小值@DecimalMax(value)
被注释的元素必须是一个数字,其值必须小于等于指定的最大值@Size(max=, min=)
被注释的元素的大小必须在指定的范围内@Digits(integer, fraction)
被注释的元素必须是一个数字,其值必须在可接受的范围内@Past
被注释的元素必须是一个过去的日期@Future
被注释的元素必须是一个将来的日期@Length(min=,max=)
被注释的字符串的大小必须在指定的范围内@Range(min=,max=,message=)
被注释的元素必须在合适的范围内
验证的参数上加上了@Valid注解
验证的类上加上了 @Validated注解
@Pattern(regexp = "((^Man$|^Woman$|^UGM$))", message = "sex 值不在可选范围") @NotNull(message = "sex 不能为空") private String sex; // 验证的参数上加上了@Valid注解 // 验证的类上加上了 @Validated注解 @Validated @RestController @RequestMapping("/api") public class PersonController { @PostMapping("/person") public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) { return ResponseEntity.ok().body(person); } }
自定义Validator
@Target({FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = RegionValidator.class) @Documented public@interface Region { String message() default "Region 值不在可选范围内"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.HashSet; publicclass RegionValidator implements ConstraintValidator<Region, String> { @Override public boolean isValid(String value, ConstraintValidatorContext context) { HashSet<Object> regions = new HashSet<>(); regions.add("China"); regions.add("China-Taiwan"); regions.add("China-HongKong"); return regions.contains(value); } }
使用验证组
// 先创建分组接口 public interface AddPersonGroup { } public interface DeletePersonGroup { } // 校验属性上加上分组 @NotNull(groups = DeletePersonGroup.class) @Null(groups = AddPersonGroup.class) private String group; @Service @Validated publicclass PersonService { public void validatePerson(@Valid Person person) { // do something } @Validated(AddPersonGroup.class) // 加上分组检验 public void validatePersonGroupForAdd(@Valid Person person) { // do something } @Validated(DeletePersonGroup.class) public void validatePersonGroupForDelete(@Valid Person person) { // do something } }
默认情况下,Spring会将此异常转换为HTTP Status 400(错误请求)。
对应的会加上异常处理器
@ExceptionHandler(ConstraintViolationException.class) ResponseEntity<String> handleConstraintViolationException(ConstraintViolationException e) { return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage()); }
12. @ControllerAdvice 和 @ExceptionHandler、@ResponseStatus
@ControllerAdvice 和 @ExceptionHandler
处理全局异常
@ControllerAdvice(assignableTypes = {PersonController.class}) //全局异常处理类 assignableTypes属性可以指定并处理特定类抛出的异常 publicclass GlobalExceptionHandler { @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<Map<String, String>> handleValidationExceptions( MethodArgumentNotValidException ex) { Map<String, String> errors = new HashMap<>(); ex.getBindingResult().getAllErrors().forEach((error) -> { String fieldName = ((FieldError) error).getField(); String errorMessage = error.getDefaultMessage(); errors.put(fieldName, errorMessage); }); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errors); } }
@ExceptionHandler 处理 Controller 级别的异常
@ExceptionHandler(value = Exception.class)// 拦截所有异常 public ResponseEntity<ErrorResponse> exceptionHandler(Exception e) { if (e instanceof IllegalArgumentException) { return ResponseEntity.status(400).body(illegalArgumentResponse); } else if (e instanceof ResourceNotFoundException) { return ResponseEntity.status(404).body(resourseNotFoundResponse); } return null; }
ResponseStatusException ResponseStatus
注解简单处理异常的方法(将异常映射为状态码)
ResponseStatusException 构造函数中的参数解释
- status :http status
- reason :response 的消息内容
- cause :抛出的异常
第一种写法
@ResponseStatus(code = HttpStatus.NOT_FOUND) public class ResourseNotFoundException2 extends RuntimeException { public ResourseNotFoundException2() { } public ResourseNotFoundException2(String message) { super(message); } }
@RestController @RequestMapping("/api") public class ResponseStatusExceptionController { @GetMapping("/resourceNotFoundException2") public void throwException3() { throw new ResourseNotFoundException2("Sorry, the resourse not found!"); } }
第二种写法
@GetMapping("/resourceNotFoundException2") public void throwException3() { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Sorry, the resourse not found!", new ResourceNotFoundException()); }
{ // 结果 "timestamp": "2019-08-21T07:11:43.744+0000", "status": 404, "error": "Not Found", "message": "Sorry, the resourse not found!", "path": "/api/resourceNotFoundException2" }
异常处理成熟做法
// 异常枚举类(所有的异常信息) public enum ErrorCode { RESOURCE_NOT_FOUND(1001, HttpStatus.NOT_FOUND, "未找到该资源"), REQUEST_VALIDATION_FAILED(1002, HttpStatus.BAD_REQUEST, "请求数据格式验证失败"); privatefinalint code; privatefinal HttpStatus status; privatefinal String message; //get,set,toString,有参构造 } // 返回的异常对象 public class ErrorReponse {//有参无参,toString privateint code; privateint status; private String message; private String path; private Instant timestamp; private HashMap<String, Object> data = new HashMap<String, Object>(); public ErrorReponse(BaseException ex, String path) { this(ex.getError().getCode(), ex.getError().getStatus().value(), ex.getError().getMessage(), path, ex.getData()); } } // BaseException(继承自 RuntimeException 的抽象类,可以看做系统中其他异常类的父类) // 系统中的异常类都要继承自这个类。 publicabstractclass BaseException extends RuntimeException { private final ErrorCode error; private final HashMap<String, Object> data = new HashMap<>(); public BaseException(ErrorCode error, Map<String, Object> data) { super(error.getMessage()); this.error = error; if (!ObjectUtils.isEmpty(data)) { this.data.putAll(data); } } protected BaseException(ErrorCode error, Map<String, Object> data, Throwable cause) { super(error.getMessage(), cause); this.error = error; if (!ObjectUtils.isEmpty(data)) { this.data.putAll(data); } } public ErrorCode getError() { return error; } public Map<String, Object> getData() { return data; } } // 自定义异常 publicclass ResourceNotFoundException extends BaseException { public ResourceNotFoundException(Map<String, Object> data) { super(ErrorCode.RESOURCE_NOT_FOUND, data); } } // 全局异常处理类 该处实例只需要handleAppException()就可以 @ControllerAdvice(assignableTypes = {ExceptionController.class}) @ResponseBody publicclass GlobalExceptionHandler { // 也可以将 BaseException 换为 RuntimeException // 因为 RuntimeException 是 BaseException 的父类 @ExceptionHandler(BaseException.class) public ResponseEntity<?> handleAppException(BaseException ex, HttpServletRequest request) { ErrorReponse representation = new ErrorReponse(ex, request.getRequestURI()); returnnew ResponseEntity<>(representation, new HttpHeaders(), ex.getError().getStatus()); } @ExceptionHandler(value = ResourceNotFoundException.class) public ResponseEntity<ErrorReponse> handleResourceNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) { // 不同层次的异常优先找到最匹配的,实例中这个先生效 ErrorReponse errorReponse = new ErrorReponse(ex, request.getRequestURI()); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorReponse); } }
13. JPA 相关注解
@Column(nullable = false)
@NotNull
是 JSR 303 Bean验证批注,它与数据库约束本身无关。
@Column(nullable = false)
: 是JPA声明列为非空的方法。
总结来说就是即前者用于验证,而后者则用于指示数据库创建表的时候对表的约束。
@Entity
声明一个类对应一个数据库实体@Table
设置表名@GeneratedValue
直接使用 JPA 内置提供的四种主键生成策略来指定主键生成策略,默认AUTO
public enum GenerationType { /** * 使用一个特定的数据库表格来保存主键 * 持久化引擎通过关系数据库的一张特定的表格来生成主键, */ TABLE, 0 /** *在某些数据库中,不支持主键自增长,比如Oracle、PostgreSQL其提供了一种叫做"序列(sequence)"的机制生成主键 */ SEQUENCE, /** * 主键自增长 */ IDENTITY, /** *把主键生成策略交给持久化引擎(persistence engine), *持久化引擎会根据数据库在以上三种主键生成 策略中选择其中一种 */ AUTO }
@Entity @Table(name = "role") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String description; 省略getter/setter...... // 上面等价于这个 @Id @GeneratedValue(generator = "IdentityIdGenerator") @GenericGenerator(name = "IdentityIdGenerator", strategy = "identity") private Long id; }
@GenericGenerator
id生成策略
@SuppressWarnings("deprecation") public DefaultIdentifierGeneratorFactory() { register( "uuid2", UUIDGenerator.class ); register( "guid", GUIDGenerator.class ); // can be done with UUIDGenerator + strategy register( "uuid", UUIDHexGenerator.class ); // "deprecated" for new use register( "uuid.hex", UUIDHexGenerator.class ); // uuid.hex is deprecated register( "assigned", Assigned.class ); register( "identity", IdentityGenerator.class ); register( "select", SelectGenerator.class ); register( "sequence", SequenceStyleGenerator.class ); register( "seqhilo", SequenceHiLoGenerator.class ); register( "increment", IncrementGenerator.class ); register( "foreign", ForeignGenerator.class ); register( "sequence-identity", SequenceIdentityGenerator.class ); register( "enhanced-sequence", SequenceStyleGenerator.class ); register( "enhanced-table", TableGenerator.class ); }
@Column
声明字段
@Column(name = "user_name", nullable = false, length=32) private String userName; @Column(columnDefinition = "tinyint(1) default 1") private Boolean enabled;
@Transient
:声明不需要与数据库映射的字段,在保存的时候不需要保存进数据库 。
static String secrect; // not persistent because of static final String secrect = "Satish"; // not persistent because of final transient String secrect; // not persistent because of transient
-
@Lob
:声明某个字段为大字段。 -
@Basic
(fetch = FetchType.EAGER/LAZY) 指定 Lob 类型数据的获取策略,EAGER 表示非延迟加载,LAZY 表示延迟加载 ; -
@Enumerated
使用枚举字段@Enumerated(EnumType.STRING) private Gender gender; -
审计相关功能
-
@CreatedDate
: 创建时间字段,被 insert 的时候,会设置值 -
@CreatedBy
:创建人字段,被 insert 的时候,会设置值 -
@LastModifiedDate
更新时间字段 -
@LastModifiedBy
更新人字段 -
@EnableJpaAuditing
:开启 JPA 审计功能// 只要继承了 AbstractAuditBase的类都会默认加上下面四个字段 @Data @AllArgsConstructor @NoArgsConstructor @MappedSuperclass @EntityListeners(value = AuditingEntityListener.class) public abstract class AbstractAuditBase { @CreatedDate @Column(updatable = false) @JsonIgnore private Instant createdAt; @LastModifiedDate @JsonIgnore private Instant updatedAt; @CreatedBy @Column(updatable = false) @JsonIgnore private String createdBy; @LastModifiedBy @JsonIgnore private String updatedBy; } // 审计功能对应地配置类(Spring Security 项目) @Configuration @EnableJpaAuditing public class AuditSecurityConfiguration { @Bean AuditorAware<String> auditorAware() { return () -> Optional.ofNullable(SecurityContextHolder.getContext()) .map(SecurityContext::getAuthentication) .filter(Authentication::isAuthenticated) .map(Authentication::getName); } }
-
-
@Modifying
修改/删除操作,注意还要配合@Transactional
注解使用。 -
@Transactional
开启事务 只能应用到 public 方法上,否则不生效
如果不配置rollbackFor
属性,那么事务只会在遇到RuntimeException
的时候才会回滚,加上rollbackFor=Exception.class
,可以让事务在遇到非运行时异常时也回滚。
- 作用于类:当把
@Transactional
注解放在类上时,表示所有该类的 public 方法都配置相同的事务属性信息。 - 作用于方法:当类配置了
@Transactional
,方法也配置了@Transactional
,方法的事务会覆盖类的事务配置信息。
@Repository public interface UserRepository extends JpaRepository<User, Integer> { @Modifying @Transactional(rollbackFor = Exception.class) void deleteByUserName(String userName); }
-
关联关系
@OneToOne
声明一对一关系@OneToMany
声明一对多关系@ManyToOne
声明多对一关系@ManyToMany
声明多对多关系@JoinColumn(name=”loginId”)
:本表中指向另一个表的外键。
-
json数据管理
-
@JsonIgnoreProperties
作用在类上用于过滤掉特定字段不返回或者不解析 -
@JsonIgnore
一般用于类的属性上,作用和上面的@JsonIgnoreProperties
一样 -
@JsonFormat
一般用来格式化 json 数据。@JsonFormat(shape=JsonFormat.Shape.STRING, pattern="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", timezone="GMT") private Date date; -
@JsonUnwrapped
扁平化对象
// 扁平化之前 @Getter @Setter @ToString public class Account { private Location location; private PersonInfo personInfo; @Getter @Setter @ToString public static class Location { private String provinceName; private String countyName; } @Getter @Setter @ToString public static class PersonInfo { private String userName; private String fullName; } } // 扁平化之前结果 { "location": { "provinceName":"湖北", "countyName":"武汉" }, "personInfo": { "userName": "coder1234", "fullName": "shaungkou" } } // 扁平化之后 @Getter @Setter @ToString public class Account { @JsonUnwrapped private Location location; @JsonUnwrapped private PersonInfo personInfo; ...... } // 扁平化之后结果 { "provinceName":"湖北", "countyName":"武汉", "userName": "coder1234", "fullName": "shaungkou" } -
-
测试相关
@ActiveProfiles
一般作用于测试类上, 用于声明生效的 Spring 配置文件
@SpringBootTest(webEnvironment = RANDOM_PORT) @ActiveProfiles("test") @Slf4j public abstract class TestBase { ...... } -
@RunWith(SpringRunner.class)
先注入这个@Autowired才能生效,有些版本不需要@RunWith(SpringRunner.class) @SpringBootTest public class FanoutProducerApplicationTests { @Autowired OrderService orderService; @Test public void contextLoads() throws Exception { orderService.makeOrder(); } } -
@Test
声明一个方法为测试方法 -
@Transactional
被声明的测试方法的数据会回滚,避免污染测试数据 -
@WithMockUser
Spring Security 提供的,用来模拟一个真实用户,并且可以赋予权限。@Test @Transactional @WithMockUser(username = "user-id-18163138155", authorities = "ROLE_TEACHER") void should_import_student_success() throws Exception { ...... }
14. Lombok相关
@Getter
用在属性、方法上提供get方法
@Setter
用在属性、方法上提供set方法
@Data
注解在类上;提供类所有属性的 get 、set、equals、canEqual、hashCode、toString 方法
@Log4j2
注解在类上;为类提供一个 属性名为log 的 log4j 日志对象,和@Log4j注解类似
@NoArgsConstructor
提供无参构造
@AllArgsConstructor
提供有参构造
RequiredArgsConstructor
提供仅有final和@NonNull修饰的属性的构造方法(被@Value的值在编译期拿不到报错)
@EqualsAndHashCode
默认情况下,会使用所有非瞬态(non-transient)和非静态(non-static)字段来生成equals和hascode方法,也可以指定具体使用哪些属性
@toString
提供toString方法,默认情况下,会输出类名、所有属性,属性会按照顺序输出,以逗号分割
@Builder
建造者模式创建对象,较清晰
15. @EnableTransactionManagement、@Transactional
@EnableTransactionManagement
开启事务管理支持
@Transactional
访问数据库的Service方法上(或类上)添加注解 @Transactional 开启事务
16. @EnableScheduling、@Scheduled
@EnableScheduling 开启计划任务的支持
@Scheduled 来申明这是一个任务,包括cron,fixDelay,fixRate等类型
@Scheduled(fixedRate = 5000) //使用fixedRate属性每隔固定时间执行 //预定任务时长,当前任务超时缩减后面任务时长补上。 //例如:已经预定任务时长为 5s。 //任务一:执行时长为6s //任务二:执行时长为4s (将任务一的时长补回来) //任务三:执行时长为7s //任务四:执行时长为3s (将任务三的时长补回来) public void reportCurrentTime(){ System.out.println("每隔5秒执行一次 "+dateFormat.format(new Date())); } @Scheduled(fixedDelay = 5000) //使用fixedDelay属性每隔固定时间执行 // 当前任务的执行时间 不影响间隔。即,两个任务之间间隔固定不变 public void reportCurrentTime(){ System.out.println("每隔5秒执行一次 "+dateFormat.format(new Date())); } @Scheduled(cron = "0 07 20 ? * *" ) //使用cron属性可按照指定时间执行,本例指的是每天20点07分执行; //cron是UNIX和类UNIX(Linux)系统下的定时任务 public void fixTimeExecution(){ System.out.println("在指定时间 "+dateFormat.format(new Date())+" 执行"); }
17、 @ServletComponentScan、@WebServlet、@WebFilter、@WebListener
@ServletComponentScan
在入口Application类上加入注解
@WebServlet
注册servlet
// 新建Servlet类,继承HttpServlet并且加入注解@WebServlet(name=“TestServlet”,urlPatterns="/test") public class TestServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getAttribute("name"); resp.getWriter().write("name:" + name); resp.getWriter().write("已处理请求"); } }
@WebFilter
添加servler过滤器
@WebFilter(urlPatterns ="/*") public class MyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("一个过滤器"); chain.doFilter(request, response); } }
@WebListener
添加servlet监听器
@WebListener public class MyListener implements ServletRequestListener { @Override public void requestInitialized (ServletRequestEvent sre) { sre.getServletRequest().setAttribute("name", "狗子"); } }
18、 Swagger相关
@Api
类上注解。控制整个类生成接口信息的内容。
- tags:类的名称。可以有多个值,表示多维度分类
- value:单个值,类的名称。唯一
- description 对 api 资源的描述
- basePath 基本路径
- position 如果配置多个 Api 想改变显示的顺序位置
- produces 如, “application/json, application/xml”
- consumes 如, “application/json, application/xml”
- protocols 协议类型,如: http, https, ws, wss.
- authorizations 高级特性认证时配置
- hidden 配置为 true ,将在文档中隐藏
@ApiOperation
写在方法上,对方法进行总体描述
- value:接口描述
- notes:提示信息
@ApiParam
写在方法参数前面。用于对参数进行描述或说明是否为必填项等说明。
- name:参数名称
- value:参数描述
- required:是否是必须
@ApiImplicitParams @ApiImplicitParam
作用在方法上
@ApiOperation(value = "用户注册", notes = "APP用户注册") @ApiImplicitParams({ @ApiImplicitParam(name = "mobile", value = "手机号码", dataType = "string", paramType = "query", example = "13802780104", required = true), @ApiImplicitParam(name = "user_name", value = "登录账号", dataType = "string", paramType = "query", example = "lihailin9073", required = true), @ApiImplicitParam(name = "password", value = "登录密码", dataType = "string", paramType = "query", example = "123456", required = true), @ApiImplicitParam(name = "validate_code", value = "注册验证码", dataType = "string", paramType = "query", example = "3679", required = true) }) public Object create() { Map<String,Object> map = new HashMap<>(); map.put("list", null); return map; }
- name :参数名。
- value : 参数的具体意义,作用。
- required : 参数是否必填。
- dataType :参数的数据类型。
- paramType :查询参数类型,这个参数不建议写明,和@RequestBody有冲突
@ApiResponses
:用于表示一组响应
@ApiResponse
:用在@ApiResponses中,一般用于表达一个错误的响应信息
@ApiResponses({ @ApiResponse(code = 400, message = "请求参数没填好"), @ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对") })
@ApiModel
实体类类上注解
- value:名称
- description:描述
@ApiModelProperty
用在方法或属性上。定义这个字段的内容。
- value:描述
- name:重写属性名
- required:是否是必须的
- example:示例内容
- hidden:是否隐藏
@ApiIgnore
用于方法或类或参数上,表示整个方法或类被忽略。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战