2团
Published on 2024-08-15 / 7 Visits
0
0

Java转换List参数至可变参数(varargs)

项目中,需要配置放行的URL列表,Spring Security提供的函数接口如下:

	public C requestMatchers(String... patterns) {
		return requestMatchers(null, patterns);
	}

配置的URL列表是List<String>类型,大致如下:

    private final List<String> AuthenticationFreeUrls = List.of(
        "/actuator/**", "/doc.html", "/webjars/**");

此时,将AuthenticationFreeUrls转换为数组,传递进requestMatchers函数即可,具体如下所示:

    @Bean
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {

        http.authorizeHttpRequests(
                (authorizeHttpRequests) -> authorizeHttpRequests.requestMatchers(
                    AuthenticationFreeUrls.toArray(new String[0])).permitAll());
        return http.build();
    }

具体可参考:How to pass an ArrayList to a varargs method parameter?

image-rztb.png


Comment