【问题标题】: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】:

你有两个选择

  1. 设置System.setProperty("prop", "value")属性硬编码
  2. 使用将覆盖所有其他属性的属性

  3. 设置系统属性硬编码

        public static void main(String[] args) {
          System.setProperty("server.tomcat.max-threads","200");
          SpringApplication.run(DemoApplication.class, args);
        }
    
  4. 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

    【讨论】:

      猜你喜欢
      • 2019-05-19
      • 2020-06-14
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2020-05-02
      • 2021-05-10
      • 2014-09-19
      • 2019-04-21
      相关资源
      最近更新 更多