Lombok、jackson、junit、spring、swagger常用注解
lombok
@val:用在局部变量前面,相当于将变量声明为final
public static void main(String[] args) {
val sets = new HashSet<String>();
val lists = new ArrayList<String>();
val maps = new HashMap<String, String>();
//=>相当于如下
final Set<String> sets2 = new HashSet<>();
final List<String> lists2 = new ArrayList<>();
final Map<String, String> maps2 = new HashMap<>();
}
@NonNull:给方法参数增加这个注解会自动在方法内对该参数进行是否为空的校验,如果为空,则抛出NPE(NullPointerException)
public void notNullExample(@NonNull String string) {
string.length();
}
//=>相当于
public void notNullExample(String string) {
if (string != null) {
string.length();
} else {
throw new NullPointerException("null");
}
}
@Cleanup:自动管理资源,用在局部变量之前,在当前变量范围内即将执行完毕退出之前会自动清理资源,自动生成try-finally这样的代码来关闭
public static void main(String[] args) {
try {
@Cleanup InputStream inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//=>相当于
InputStream inputStream = null;
try {
inputStream = new FileInputStream(args[0]);
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Getter/@Setter:用在属性上,再也不用自己手写setter和getter方法了,还可以指定访问范
@Setter(AccessLevel.PUBLIC)
@Getter(AccessLevel.PROTECTED)
private int id;
private String shap;
@ToString:用在类上,可以自动覆写toString方法,当然还可以加其他参数,例如@ToString(exclude=”id”)排除id属性,或者@ToString(callSuper=true, includeFieldNames=true)调用父类的toString方法,包含所有属性
@ToString(exclude = "id", callSuper = true, includeFieldNames = true)
public class LombokDemo {
private int id;
private String name;
private int age;
public static void main(String[] args) {
//输出LombokDemo(super=LombokDemo@48524010, name=null, age=0)
System.out.println(new LombokDemo());
}
}
@EqualsAndHashCode:用在类上,自动生成equals方法和hashCode方法
@EqualsAndHashCode(exclude = {"id", "shape"}, callSuper = false)
public class LombokDemo {
private int id;
private String shap;
}
@NoArgsConstructor, @RequiredArgsConstructor and @AllArgsConstructor:用在类上,自动生成无参构造和使用所有参数的构造函数以及把所有@NonNull属性作为参数的构造函数,如果指定staticName = “of”参数,同时还会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多
@NoArgsConstructor
@RequiredArgsConstructor(staticName = "of")
@AllArgsConstructor
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
public static void main(String[] args) {
new LombokDemo(1, "circle");
//使用静态工厂方法
LombokDemo.of(2, "circle");
//无参构造
new LombokDemo();
//包含所有参数
new LombokDemo(1, "circle", 2);
}
}
@Data:注解在类上,相当于同时使用了@ToString、@EqualsAndHashCode、@Getter、@Setter、@RequiredArgsConstrutor这些注解,对于POJO类十分有用
import lombok.Data;
@Data
public class Menu {
private String shopId;
private String skuMenuId;
private String skuName;
private String normalizeSkuName;
private String dishMenuId;
private String dishName;
private String dishNum;
//默认阈值
private float thresHold = 0;
//新阈值
private float newThresHold = 0;
//总得分
private float totalScore = 0;
}
@Value:用在类上,是@Data的不可变形式,相当于为属性添加final声明,只提供getter方法,而不提供setter方法
@Value
public class LombokDemo {
@NonNull
private int id;
@NonNull
private String shap;
private int age;
//相当于
private final int id;
public int getId() {
return this.id;
}
...
}
@Builder:用在类、构造器、方法上,为你提供复杂的builder APIs,让你可以像如下方式一样调用Person.builder().name(“Adam Savage”).city(“San Francisco”).job(“Mythbusters”).job(“Unchained Reaction”).build();更多说明参考Builder
@Builder
public class BuilderExample {
private String name;
private int age;
@Singular
private Set<String> occupations;
public static void main(String[] args) {
BuilderExample test = BuilderExample.builder().age(11).name("test").build();
}
}
@SneakyThrows:自动抛受检异常,而无需显式在方法上使用throws语句
import lombok.SneakyThrows;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class Test {
@SneakyThrows()
public void read() {
InputStream inputStream = new FileInputStream("");
}
@SneakyThrows
public void write() {
throw new UnsupportedEncodingException();
}
//相当于
public void read() throws FileNotFoundException {
InputStream inputStream = new FileInputStream("");
}
public void write() throws UnsupportedEncodingException {
throw new UnsupportedEncodingException();
}
}
@Synchronized:用在方法上,将方法声明为同步的,并自动加锁,而锁对象是一个私有的属性l o c k 或 lock或lock或LOCK,而java中的synchronized关键字锁对象是this,锁在this或者自己的类对象上存在副作用,就是你不能阻止非受控代码去锁this或者类对象,这可能会导致竞争条件或者其它线程错误
import lombok.SneakyThrows;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
public class Test {
@SneakyThrows()
public void read() {
InputStream inputStream = new FileInputStream("");
}
@SneakyThrows
public void write() {
throw new UnsupportedEncodingException();
}
//相当于
public void read() throws FileNotFoundException {
InputStream inputStream = new FileInputStream("");
}
public void write() throws UnsupportedEncodingException {
throw new UnsupportedEncodingException();
}
}
@Getter(lazy=true):可以替代经典的Double Check Lock样板代码
public class GetterLazyExample {
@Getter(lazy = true)
private final double[] cached = expensive();
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
// 相当于如下所示:
import java.util.concurrent.atomic.AtomicReference;
public class GetterLazyExample {
private final AtomicReference<java.lang.Object> cached = new AtomicReference<>();
public double[] getCached() {
java.lang.Object value = this.cached.get();
if (value == null) {
synchronized (this.cached) {
value = this.cached.get();
if (value == null) {
final double[] actualValue = expensive();
value = actualValue == null ? this.cached : actualValue;
this.cached.set(value);
}
}
}
return (double[]) (value == this.cached ? null : value);
}
private double[] expensive() {
double[] result = new double[1000000];
for (int i = 0; i < result.length; i++) {
result[i] = Math.asin(i);
}
return result;
}
}
@Log:根据不同的注解生成不同类型的log对象,但是实例名称都是log,有六种可选实现类:
@CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);
@Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());
@Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);
@Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);
@Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
@XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
jackson
@JsonPropertyOrder(value={"pname1","pname2"}) 改变子属性在JSON序列化中的默认定义的顺序。如:param1在先,param2在后。
@JsonIgnore 排除某个属性不做序列化与反序列化
@JsonProperty(anotherName) 为某个属性换一个名称,体现在JSON数据里面
@JsonInclude(JsonInclude.Include.NON_NULL) 排除为空的元素不做序列化反序列化
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") 指定日期类型的属性格式
junit
@Test 声明一个测试方法
@BeforeAll 在当前类的所有测试方法之前执行,注解在静态方法上
@AfterAll 在当前类的所有测试方法之后执行,注解在静态方法上
@BeforeEach 在当前类的所有测试方法之前执行,注解在非静态方法上
@AfterEach 在当前类的所有测试方法之后执行,注解在非静态方法上
@ExtendWith(SpringExtension.class) 类class定义上
spring
| HTTP协议组成 | 协议内容示例 | 对应Spring注解 |
|---|---|---|
| path info传参 | /articles/12 (查询id为12的文章,12是参数) | @PathVariable |
| URL Query String传参 | /articles?id=12 | @RequestParam |
| Body 传参 | Content-Type: multipart/form-data | @RequestParam |
| Body 传参 | Content-Type: application/json,或其他自定义格式 | @RequestBody |
| Headers 传参 | @RequestHeader |
@RequestBody与@ResponseBody
-
@RequestBody修饰请求参数,注解用于接收HTTP的body,默认是使用JSON的格式
-
@ResponseBody修饰返回值,注解用于在HTTP的body中携带响应数据,默认是使用JSON的格式。如果不加该注解,spring响应字符串类型,是跳转到模板页面或jsp页面的开发模式。说白了:加上这个注解你开发的是一个数据接口,不加这个注解你开发的是一个页面跳转控制器。
//注意并不要求@RequestBody与@ResponseBody成对使用。 public @ResponseBody AjaxResponse saveArticle(@RequestBody ArticleVO article)
@RequestMapping注解
-
value: 应用请求端点,最核心的属性,用于标志请求处理方法的唯一性;
-
method: HTTP协议的method类型, 如:GET、POST、PUT、DELETE等;
-
consumes: HTTP协议请求内容的数据类型(Content-Type),例如application/json, text/html;
-
produces: HTTP协议响应内容的数据类型。下文会详细讲解。
-
params: HTTP请求中必须包含某些参数值的时候,才允许被注解标注的方法处理请求。
-
headers: HTTP请求中必须包含某些指定的header值,才允许被注解标注的方法处理请求。
@RequestMapping(value = "/article", method = POST) @PostMapping(value = "/article")上面代码中两种写法起到的是一样的效果,也就是PostMapping等同于@RequestMapping的method等于POST。同理:@GetMapping、@PutMapping、@DeleteMapping也都是简写的方式。
@RestController与@Controller
@Controller注解是开发中最常使用的注解,它的作用有两层含义:
- 一是告诉Spring,被该注解标注的类是一个Spring的Bean,需要被注入到Spring的上下文环境中。
- 二是该类里面所有被RequestMapping标注的注解都是HTTP服务端点。
@RestController相当于 @Controller和@ResponseBody结合。它有两层含义:
- 一是作为Controller的作用,将控制器类注入到Spring上下文环境,该类RequestMapping标注方法为HTTP服务端点。
- 二是作为ResponseBody的作用,请求响应默认使用的序列化方式是JSON,而不是跳转到jsp或模板页面。
@PathVariable 与@RequestParam
PathVariable用于URI上的{参数},如下方法用于删除一篇文章,其中id为文章id。如:我们的请求URL为“/article/1”,那么将匹配DeleteMapping并且PathVariable接收参数id=1。而RequestParam用于接收普通表单方式或者ajax模拟表单提交的参数数据。
@DeleteMapping("/article/{id}")
public @ResponseBody AjaxResponse deleteArticle(@PathVariable Long id) {
@PostMapping("/article")
public @ResponseBody AjaxResponse deleteArticle(@RequestParam Long d) {
swagger
@Api:用在Controller控制器类上
属性tags="说明该类的功能及作用"
@ApiOperation:用在Controller控制器类的请求的方法上
value="说明方法的用途、作用"
notes="方法的备注说明"
@ApiImplicitParams:用在请求的方法上,表示一组参数说明
@ApiImplicitParam:请求方法中参数的说明
name:参数名
value:参数的汉字说明、解释、用途
required:参数是否必须传,布尔类型
paramType:参数的类型,即参数存储位置或提交方式
· header --> Http的Header携带的参数的获取:@RequestHeader
· query --> 请求参数的获取:@RequestParam (如上面的例子)
· path(用于restful接口)--> 请求参数的获取:@PathVariable
· body(不常用)
· form(不常用)
dataType:参数类型,默认String,其它值dataType="Integer"
defaultValue:参数的默认值

浙公网安备 33010602011771号