如何在Java 8中进行条件方法链接

sap*_*apy 4 java method-chaining java-8 spring-boot

我有一个spring security配置方法.我希望antMatchers("/**/**").permitAll()仅在条件匹配时才链接特定方法.这样的事情{dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} .当然,这不是一个有效的语法,最重要的做法是什么.寻找menimum编码.

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .cors().disable()
            .authorizeRequests()
            {dev == true ? .antMatchers("/**/**").permitAll(): ()->{}} //dev only. NEVER enable on prod 
                .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/")
                .loginProcessingUrl("/api/signin")
                .successHandler(authSuccessHandler())
                .failureHandler(authFailureHandler())
                .permitAll()
                .and()
            .logout()
                .permitAll();
    }
Run Code Online (Sandbox Code Playgroud)

Mic*_*ael 6

唯一的方法是将中间对象分配给变量.

WhateverAuthorizeRequestsReturns partial = http
    .csrf().disable()
    .cors().disable()
    .authorizeRequests();

if (dev) // note: you don't need 'dev == true' like you had
{
    partial.someOptionalThing();
    // if the type is immutable then you need to reassign e.g.:
    // partial = partial.someOptionalThing()
}

partial.something()
    .somethingElse()
    .andTheRest();
Run Code Online (Sandbox Code Playgroud)


Rez*_*iri 5

如果您只想允许基于布尔值访问特定路径,您可以尝试以下操作:

 http
        .csrf().disable()
        .cors().disable()
        .authorizeRequests()
        .antMatchers(dev ? "/**/**":"invalid-path").permitAll()
            .antMatchers("/", "/signup", "/static/**", "/api/sigin", "/api/signup", "**/favicon.ico").permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/")
            .loginProcessingUrl("/api/signin")
            .successHandler(authSuccessHandler())
            .failureHandler(authFailureHandler())
            .permitAll()
            .and()
        .logout()
            .permitAll();
Run Code Online (Sandbox Code Playgroud)