Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 声明类型不能为null_Java_Spring_Validation_Null_Annotations - Fatal编程技术网

Java 声明类型不能为null

Java 声明类型不能为null,java,spring,validation,null,annotations,Java,Spring,Validation,Null,Annotations,我正在使用来处理null参数和方法声明中的返回值 例如: @Validated public interface MyService { @NotNull User createNewUser(@NotNull Username username, @NotNull Password password); } 其中,Username和Password只是用户名和密码字符串的包装,User是表示用户帐户的类,@NotNull是javax.validation.constraints.No

我正在使用来处理
null
参数和方法声明中的返回值

例如:

@Validated
public interface MyService {
    @NotNull User createNewUser(@NotNull Username username, @NotNull Password password);
}
其中,
Username
Password
只是用户名和密码字符串的包装,
User
是表示用户帐户的类,
@NotNull
javax.validation.constraints.NotNull

实际上,
MyService
有更多的方法,还有其他类,我决定用
@NotNull
声明它们的参数和返回类型,就像上面的例子一样。但我认为我的代码远远不够优雅,因为它充满了样板
@NotNull
声明

所以我觉得如果我能做到这一点就太好了

@NotNull
public class Username {...}

@NotNull
public class User {...}

@NotNull
public class Password {...}
并期望
用户名
密码
用户
等类型的变量不能为
,这样我就不必在其他任何地方重复在这些变量前面加上
@NotNull
(实际上,
@NotNull
注释不允许与类声明一起使用)


是否可以通过某些方式实现这一点?

像这样的注释最终会在带注释的方法周围有一个代理。由于您希望进行空检查,您将无法代理甚至未创建的对象:)因此,我认为您所能做的就是使用SpringAOP围绕所有使用用户名或密码作为参数的方法定义一个代理。请参阅中的args选项。 您可能最终会遇到这样的情况(尚未测试):

…或者深入挖掘并围绕方法签名应用一些逻辑(例如,使用参数类型数组并行处理参数数组)

final MethodSignature MethodSignature=(MethodSignature)pjp.getSignature();
Method=methodSignature.getMethod();
类[]paramTypes=method.getParameterTypes());
希望这有帮助, 格格利

<aop:config>
  <aop:aspect id="nullValidation" ref="nullValidatorAspect">
    <aop:around pointcut="args(foo.bar.Username,..)" method="validateNull"/>
    <aop:around pointcut="args(foo.bar.Password,..)" method="validateNull"/>
  </aop:aspect>
</aop:config>
public Object validateNull(ProceedingJoinPoint pjp) {
  Object[] args = pjp.getArgs(); 
  for ( Object arg : args ) {
     //not null validation
  }
  pjp.proceed();
}
final MethodSignature methodSignature = (MethodSignature)pjp.getSignature();
Method method = methodSignature.getMethod();
Class<?>[] paramTypes = method.getParameterTypes());