Passing varargs to Spring spEL causes “Method cannot be found on com.sun.proxy”

我只是一个虾纸丫 提交于 2019-12-04 05:31:56

问题


I try to write custom class for permissions evaluation, so it can be used with Spring Security @PreAuthorize and Spring Expression Language like for example this (authority is just a regular Spring component with some role names):

@PreAuthorize("@permissionEvaluator.anyOfRoles(@authority.ADMIN)")

The PermissionEvaluator#anyOfRoles method declaration looks like follows:

boolean anyOfRoles(String... roles)

As shown this method takes varargs of String type. It works fine when only one parameter is passed (as on the example above) but calling it with more than one argument, eg.

@PreAuthorize("@permissionEvaluator.anyOfRoles(@authority.ADMIN, @authority.USER)")

causes

org.springframework.expression.spel.SpelEvaluationException: EL1004E: Method call: Method anyOfRoles(java.lang.String,java.lang.String) cannot be found on com.sun.proxy.$Proxy132 type

to be thrown. It still works when called with an array of Strings (basically same as varargs, which is just syntactic sugar), like this:

@PreAuthorize("@permissionEvaluator.anyOfRoles(new String[] { @authority.ADMIN, @authority.USER })")

I tried to look some additional info about passing varargs with spEL but Spring documentation only enigmatically mentions in spEL documentation that

Varargs are also supported.

What might be the cause of this exception and is there other workaround than passing array in spEL?


回答1:


What version of Spring are you using? I just ran this test case with 4.3.12 and it worked fine...

@SpringBootApplication
public class So46953884Application {

    public static void main(String[] args) {
        SpringApplication.run(So46953884Application.class, args);
    }

    @Value("#{foo.foo('a', 'b')}")
    private String foo;

    @Bean
    public ApplicationRunner runner() {
        return args -> System.out.println(foo);
    }

    @Bean
    public Foo foo() {
        return new Foo();
    }

    public static class Foo {

        public String foo(String... strings) {
            return "filled: " + Arrays.toString(strings);
        }

    }

}

Result:

filled: [a, b]


来源:https://stackoverflow.com/questions/46953884/passing-varargs-to-spring-spel-causes-method-cannot-be-found-on-com-sun-proxy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!