简体   繁体   English

如何在运行时切换Spring配置文件?

[英]How to switch Spring profiles on runtime?

Currently I inject to my application properties via @Value and it works just fine. 目前,我通过@Value注入我的应用程序属性,并且效果很好。 Now I want my application to support more than one configuration, which means its @Value should return different value each time. 现在,我希望我的应用程序支持多个配置,这意味着其@Value每次应返回不同的值。

I read about spring profiles, but I couldn't understand how can I switch profile on runtime. 我阅读了有关Spring配置文件的内容,但我不明白如何在运行时切换配置文件。 Is it even possible? 可能吗

What I really need is to load all of the configuration when the server starts and choose its profile dynamically when a request arrives - each request should have one set of configurations. 我真正需要的是在服务器启动时加载所有配置,并在请求到达时动态选择其配置文件-每个请求都应具有一组配置。

Switching Spring profiles during runtime is not a good practice. 在运行时切换Spring配置文件不是一个好习惯。 Spring profile is meant to be used as a way to manage your application across different environments . Spring概要文件旨在用作在不同环境中管理应用程序的一种方式。

Spring Profiles provide a way to segregate parts of your application configuration and make it be available only in certain environments Spring Profiles提供了一种分离应用程序配置的各部分并使之仅在某些环境中可用的方法

If you have a variable that needs to change dynamically for every incoming requests, consider these several options: 如果您的变量需要针对每个传入请求进行动态更改,请考虑以下几个选项:

  • Store the value in DB, cache on start, and fetch based on the incoming request parameters/body 将值存储在数据库中,在启动时进行缓存,并根据传入的请求参数/主体进行获取
  • Infer the value from incoming request parameters/body 从传入的请求参数/主体推断值
  • Store all the possible values in properties file, load on start, and select based on incoming request parameters/body 将所有可能的值存储在属性文件中,在启动时加载,然后根据传入的请求参数/主体进行选择
  • Store all the possible values as enum/constants and select bsaed on incoming request parameters/body 将所有可能的值存储为枚举/常量,并在传入的请求参数/正文中选择bsaed

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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