@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
如何理解这个(request, response, authException) ->
,它在哪里找到所有这3个变量?在课堂上没有。
它是什么->
?
答案 0 :(得分:4)
AuthenticationEntryPoint
是一个功能接口(只包含一个公共方法的接口:commence
)。可以使用Java Lambda表达式创建功能接口类。
在pre java 8编程风格中,您可以使用anonymous class:
@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
AuthenticationEntryPoint entryPoint = new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}
};
return entryPoint;
}
这里我们创建一个AuthenticationEntryPoint
匿名类,我们在其中实现AuthenticationEntryPoint.commence()
的行为。
Java 8 lambda表达式提供语法糖来将代码简化为:
return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
调用时, request, response, authException
将提供给方法。
此处有更多信息:https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html