jpganz18 jpganz18 - 2 months ago 13
Java Question

Is it possible to set properties for a Spring Boot application from a bean?

I was wondering if there is any way to do this.

I want to hardcode a property (I know might not be the best), let's say I want to run my application always on port XXX or any other configuration without using a

.properties
.

Is there any way I can do this from the main? or a configuration bean?

Thanks.

Answer

Take a look at this for how to configure a port: Spring Boot - how to configure port

Relevant code is this:

@Controller
public class ServletConfig {
    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {
      return (container -> {
        container.setPort(8012);
    });
}

In general, most properties that can be configured via application.properties can also be configured through a Java bean. But, I would suggest using application.properties if you can. It allows you to change properties, without having to change source code.

EDIT:

Some other code from the posted link you might find useful:

HashMap<String, Object> props = new HashMap<>();
props.put("server.port", 9999);

new SpringApplicationBuilder()
  .sources(SampleController.class)                
  .properties(props)
  .run(args);
Comments