【问题标题】:Spring Boot: Make property non-configurableSpring Boot:使属性不可配置
【发布时间】:2017-12-05 13:06:12
【问题描述】:
在 Spring Boot 中,externalize my configuration 有几个选项。但是,我怎样才能使这些属性不可配置,即只读。
具体来说,我想将server.tomcat.max-threads 设置为固定值,并且不希望将要启动应用程序的人能够更改它。例如,这可以通过将其作为命令行参数传递来轻松完成。
默认情况下这可能是不可能的,也许有人可以提出解决方法?
【问题讨论】:
标签:
java
spring
spring-boot
【解决方案1】:
你有两个选择
- 设置
System.setProperty("prop", "value")属性硬编码
使用将覆盖所有其他属性的属性
-
设置系统属性硬编码
public static void main(String[] args) {
System.setProperty("server.tomcat.max-threads","200");
SpringApplication.run(DemoApplication.class, args);
}
-
secure.properties 中的属性将覆盖所有其他属性(请参阅Prevent overriding some property in application.properties - Spring Boot)
@Configuration
public class SecurePropertiesConfig {
@Autowired
private ConfigurableEnvironment env;
@Autowired
public void setConfigurableEnvironment(ConfigurableEnvironment env) {
try {
final Resource resource = new
ClassPathResource("secure.properties");
env.getPropertySources().addFirst(new
PropertiesPropertySource(resource.getFilename(),
PropertiesLoaderUtils.loadProperties(resource)));
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage(), ex);
}
}
【解决方案2】:
我最终实现了一个ApplicationContextInitializer (Docu),它在其initialize() 方法中简单地以编程方式设置静态值:
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
ConfigurableEnvironment environment = applicationContext.getEnvironment();
Map<String, Object> props = new HashMap<>();
props.put(MAX_THREADS, MAX_THREADS_VAL);
environment.getPropertySources().addFirst(new MapPropertySource("tomcatConfigProperties", props));
}
在这里找到了另一种可能的解决方案:Prevent overriding some property in application.properties - Spring Boot