Using @Value with condition in spring in order to map value to string

被刻印的时光 ゝ 提交于 2020-08-27 06:34:05

问题


I have a application.properites file with the following:

xxx.xxx = sandbox
xxx.sandbox = 123
xxx.production = 456

I would like to map to a string value 123 in case xxx.xxx == sandbox and 456 in case xxx.xxx == production

...
public class temp { 

 @Value("${??????}")
    private String token;
}

is it possible to fill in a condition incited of the ?????? that will map the token to 123 or 456 according to xxx.xxx ?


回答1:


A simple way in case someone will hit this question:

@Value("#{'${xxx.xxx}'=='sandbox' ? '${xxx.sandbox}' : '${xxx.production}'}")

I just think it is much easier that start working with profiles.




回答2:


You can use Spring Profiles, so you can have a property file for each enviroment.

Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Any @Component or @Configuration can be marked with @Profile to limit when it is loaded

You can see more here http://www.baeldung.com/spring-profiles

http://www.mkyong.com/spring/spring-profiles-example/

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-profiles.html



来源:https://stackoverflow.com/questions/37143562/using-value-with-condition-in-spring-in-order-to-map-value-to-string

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