简体   繁体   中英

Spring Boot WebMvcConfigurer called twice, not resolving @Value second time

I have a Spring Boot application, using annotation-based configuration. I'm trying to set some CORS rules up, but want the flexibility of having @Value variables to use so I can keep localhost connections out of the production server, etc. I found sample code; the problem is that my class is being called twice, and the second time the @Value variable does not translate into the value from my configuration file. The first time it does translate, but that is overwritten.

Here's some sample code:

@Configuration
@EnableWebMvc
@EnableScheduling
@ComponentScan(basePackages= {"mysite.controller"})
public class ServletContextConfig implements WebMvcConfigurer{

    @Value("#{'${baselineCorsOrigins}'.split(',')}")
    private List<String> rawOrigins;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
        .allowedOrigins(getOrigin())
        .maxAge(3600)
        .exposedHeaders("Access-Control-Allow-Origin");
    }
    
    public String[] getOrigin() {
        int size = rawOrigins.size();
        String[] originArray = new String[size];
        return rawOrigins.toArray(originArray);
    }

The example works the first time the class is called. If I put a logging statement in there I can see the values translating. However, the second time it is called the value is ${baselineCorsOrigins}. Unfortunately that's the version that wins.

I've reverted to hard-coding the allowed values, but that is far from ideal. Is there a known workaround?

The solution was 'do it differently altogether'. Instead of a implementor of WebMvcConfigurer, the code works in an extender of WebSecurityConfigurerAdapter.

@Configuration
@EnableWebSecurity
public class AppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("#{'${baseline.corsOrigins}'.split(',')}")
    private List<String> corsOrigins;


    private static final String[] AUTH_WHITELIST = {
            // -- tickTock health check
            "/tickTock"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
        .antMatchers(AUTH_WHITELIST).permitAll()
        .anyRequest().authenticated()
        .and().cors().configurationSource(request -> {
            var cors = new CorsConfiguration();
            cors.setAllowedOrigins(corsOrigins);
            cors.setAllowedHeaders(List.of("*"));
            cors.setExposedHeaders(Arrays.asList("Access-Control-Allow-Origin"));
            return cors;
            });
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM