如内容所示的Java注解什么意思?
我在 spring-security-jwt-guide 看到一个 看不懂的写法,其中AuthController
有如下代码:
/** * @author shuang.kou
* @description 认证授权
**/
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor(onConstructor = @__(@Autowired)) //此处@__没看懂
@Api(tags = "认证")
public class AuthController {
private final AuthService authService;
@PostMapping("/login")
@ApiOperation("登录")
public ResponseEntity<Void> login(@RequestBody LoginRequest loginRequest) {
String token = authService.createToken(loginRequest);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.set(SecurityConstants.TOKEN_HEADER, token);
return new ResponseEntity<>(httpHeaders, HttpStatus.OK);
}
@PostMapping("/logout")
@ApiOperation("退出")
public ResponseEntity<Void> logout() {
authService.removeToken();
return new ResponseEntity<>(HttpStatus.OK);
}
}
请问:
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
中的 @__
是什么意思?
回答:
lombok doc
The reason of the weird syntax is to make this feature work in javac 7 compilers; the
@__
type is an annotation reference to the annotation type__
(double underscore) which doesn't actually exist; this makes javac 7 delay aborting the compilation process due to an error because it is possible an annotation processor will later create the__
type. Instead, lombok applies the annotations and removes the references so that the error will never actually occur. The point is: The__
type must not exist, otherwise the feature does not work. In the rare case that the__
type does exist (and is imported or in the package), you can simply add more underscores. Technically any non-existent type would work, but to maintain consistency and readability and catch erroneous use, lombok considers it an error if the 'wrapper' annotation is anything but a series of underscores.In javac8, the above feature should work but due to a bug in javac8 it does not. However, starting in javac8, if the parameter name does not exist in the annotation type, compilation proceeds to a phase where lombok can fix it.
To reiterate: This feature can disappear at any time; if you use this feature, be prepared to adjust your code when we find a nicer way of implementing this feature, or, if a future version of javac forces us to remove this feature entirely with no alternative.
The onX parameter is not legal on any type-wide variant. For example, a @Getter annotation on a class does not support onMethod.
回答:
- 含义
@RequiredArgsConstructor会将类的每一个final字段或者non-null字段生成一个构造方法 - 用法
@RequiredArgsConstructor(onConstructor =@_(@Autowired)) 写在类上可以代替@AutoWired注解
需要注意的是在注入时需要用final定义,或者使用@notnull注解
如: private final ImgService imgService;
以上是 如内容所示的Java注解什么意思? 的全部内容, 来源链接: utcz.com/p/944410.html