简体   繁体   中英

Loading String[] from properties file into origins field of @CrossOrigin using property placeholder expression

In my spring boot application I have the following controller

@RestController(value = "ProjectController")
@CrossOrigin(origins = {"${app.api.settings.cross-origin.urls}"})
public class ProjectController {
   // some request mapping methods
}

The property app.api.settings.cross-origin.urls is already a key having comma separated valid urls in application.properties file like

app.api.settings.cross-origin.urls=http://localhost:3000, http://localhost:7070

This approach works till I have only single value like

app.api.settings.cross-origin.urls=http://localhost:3000 but not for comma separated values. The origins field inside @CrossOrigin is of type String[] still it does not convert into String[] automatically. I mean there should be some way to achieve this provided by the framework. Not a work around. I can achieve using comma separated urls from properties files using @Value into a List<String> or String[] as a field inside a @Configuration class like below

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

    @Value("${app.api.settings.cross-origin.urls}")
    private String[] consumerUiOrigins;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
         registry
           .addMapping("/api/**")
           .allowedOrigins(consumerUiOrigins);
    }
}

But this would be a global configuration having application wide applicability. I want to stick to the more fine grained @CrossOrigin annoation based CORS configuration.

So I put my question clearly below.

Is it possible to inject comma separated value from properties file as String[] using property plcaholer expression ( ${*} ) into spring annotation fields having the same type ie String[] ????? If yes then how??? If no then can we tweak some core framework classes to achieve this??? Anyone please help....

PS - Please do not mark my question as duplicate of Use Spring Properties in Java with CrossOrigin Annotation or in Spring-Config XML

My question is more on usage of property placholder expressions inside spring annotation fields having multi element type like String[] and less on the configuration of CORS in spring applications.

Try doing as below in application.properties:

app.api.settings.cross-origin.urls="http://localhost:3000","http://localhost:7070"

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