1)lombok介紹
lombok能夠極大的簡化消除我們寫的代碼,使用註解的方式省略get set toString….等方法,使得代碼看起來更加的美觀。lombok是在編譯時候生成對應的方法的,所以在性能上面大家完全不用擔心,是與我們寫上get set方法是一樣的。它自帶了這些標籤
lombok使用(常用的幾個註釋)
2)安裝lombok插件
IDEA下 File—setting—plugin–搜索lombok–安裝 重啓便可以了
eclipse下,先下載lombok jar包。使用cmd命令java -jar 你的lombok jar路徑,然後會彈出一個框 這裏會自動搜索你的eclipse安裝路徑(如果搜索不到,自行選擇),如下圖
安裝完成後在你的eclipse安裝路徑下回有一個lombok.jar。同時你也可以看看ecliipse.ini裏面是否多了個lombok
重啓你的eclipse,這樣那些報錯說沒有get set方法的類就好了
3)項目使用中引入
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
<scope>provided</scope>
</dependency>
4)常用註解
@Data:註解在類上,將類提供的所有屬性都添加get、set方法,並添加、equals、canEquals、hashCode、toString方法
@Setter:註解在類上,爲所有屬性添加set方法、註解在屬性上爲該屬性提供set方法
@Getter:註解在類上,爲所有的屬性添加get方法、註解在屬性上爲該屬性提供get方法
@NotNull:在參數中使用時,如果調用時傳了null值,就會拋出空指針異常
@Synchronized 用於方法,可以鎖定指定的對象,如果不指定,則默認創建一個對象鎖定
@Log作用於類,創建一個log屬性
@Builder:使用builder模式創建對象
@NoArgsConstructor:創建一個無參構造函數
@AllArgsConstructor:創建一個全參構造函數, 替代@Autowired構造注入,多個bean 注入時更加清晰
@Slf4j
@Configuration
@AllArgsConstructor
public class RouterFunctionConfiguration {
private final HystrixFallbackHandler hystrixFallbackHandler;
private final ImageCodeHandler imageCodeHandler;
}
@Slf4j
@Configuration
public class RouterFunctionConfiguration {
@Autowired
private HystrixFallbackHandler hystrixFallbackHandler;
@Autowired
private ImageCodeHandler imageCodeHandler;
}
@ToString:創建一個toString方法
@Accessors(chain = true)使用鏈式設置屬性,set方法返回的是this對象。
@RequiredArgsConstructor:創建對象, 例: 在class上添加@RequiredArgsConstructor(staticName = “of”)會創建生成一個靜態方法
@UtilityClass:工具類再也不用定義static的方法了,直接就可以Class.Method 使用
@UtilityClass
public class Utility {
public String getName() {
return "name";
}
}
public static void main(String[] args) {
System.out.println(Utility.getName());
}
@ExtensionMethod:設置父類
@FieldDefaults:設置屬性的使用範圍,如private、public等,也可以設置屬性是否被final修飾。
@SneakyThrows
@SneakyThrows
private void checkCode(ServerHttpRequest request) {
String code = request.getQueryParams().getFirst("code");
if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("驗證碼不能爲空");
}
redisTemplate.delete(key);
}
// 不使用就要加這個拋出
private void checkCode(ServerHttpRequest request) throws ValidateCodeException {
String code = request.getQueryParams().getFirst("code");
if (StrUtil.isBlank(code)) {
throw new ValidateCodeException("驗證碼不能爲空");
}
}
@EqualsAndHashCode:重寫equals和hashcode方法。
@Cleanup: 清理流對象,不用手動去關閉流
@Cleanup
OutputStream outStream = new FileOutputStream(new File("text.txt"));
@Cleanup
InputStream inStream = new FileInputStream(new File("text2.txt"));
byte[] b = new byte[65536];
while (true) {
int r = inStream.read(b);
if (r == -1) break;
outStream.write(b, 0, r);
}
參考文章:https://blog.csdn.net/qq_26118603/article/details/78944704
參考文章:https://blog.csdn.net/hh1sdfsf56456/article/details/81331676