Чечил Крым Чечил Крым - 27 days ago 17
Java Question

Understanding java 8 lambda expressions used to define Spring Security beans

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


How to understand this
(request, response, authException) ->
, Where did it find all these 3 variables? there are not in class field.

And what is it
->
?

Answer

AuthenticationEntryPoint is a functional interface (a interface containing only one public method: commence). Functional interfaces classes can be created using Java Lambda expressions.

In a pre java 8 programming style you could use an 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;
}

Here we create an AuthenticationEntryPoint anonymous class in which we implement the behaviour of AuthenticationEntryPoint.commence().

Java 8 lambda expressions provide syntactic sugar to reduce the code to just:

return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);

request, response, authException will be provided to the method when called.

More info here: https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html