简体   繁体   中英

Spring Boot: Make property non-configurable

In Spring Boot I have several options to externalize my configuration . However, how can I make such properties non-configurable , ie readonly.

Concretly, I want to set server.tomcat.max-threads to a fixed value and do not want somebody who is going to start the application to have the ability to change it. This could easily be done by passing it as a command line argument for instance.

It's probably not possible by default, maybe someone could suggest workarounds?

You have 2 options

  1. Set System.setProperty("prop", "value") Property hard coded
  2. Use properties that will override all other properties

  3. Set system property hard coded

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

I ended up implementing an ApplicationContextInitializer ( Docu ), which in its initialize() method simply sets the static value programatically:

@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));

}

Another possible solution was found here: Prevent overriding some property in application.properties - Spring Boot

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