Чечил Крым Чечил Крым - 1 year ago 103
Java Question

Understanding java 8 lambda expressions used to define Spring Security beans

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 Source

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:

public AuthenticationEntryPoint unauthorizedEntryPoint() {
    AuthenticationEntryPoint entryPoint = new AuthenticationEntryPoint() {
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
    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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download