理解用于定义 Spring Security bean 的 java 8 lambda 表达式

Чеч*_*рым 2 java lambda spring spring-security java-8

@Bean
    public AuthenticationEntryPoint unauthorizedEntryPoint() {
        return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
Run Code Online (Sandbox Code Playgroud)

如何理解这一点(request, response, authException) ->,它在哪里找到所有这三个变量?没有在类领域。

它是什么 ->?

cod*_*ent 5

AuthenticationEntryPoint是一个函数接口(一个只包含一个公共方法的接口:)commence。可以使用 Java Lambda 表达式创建功能接口实现。

在 java 8 之前的编程风格中,您可以使用匿名类:

@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;
}
Run Code Online (Sandbox Code Playgroud)

在这里,我们创建了一个AuthenticationEntryPoint匿名类,在其中实现了 的行为AuthenticationEntryPoint.commence()。

Java 8 lambda 表达式提供了语法糖来将代码简化为:

return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
Run Code Online (Sandbox Code Playgroud)

request, response, authException 将在调用时提供给方法。

更多信息:https : //docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html