How do you set startup parameters in Spring Boot?
In a Spring Boot application, startup parameters can be set as follows:
- Set parameters in the application.properties or application.yml file.
In the application.properties file, you can use the following format to set startup parameters: - – The server is running on port 8080 with logging set to DEBUG for the root level.
- You can configure startup parameters using the following format in the application.yml file.
- server:
port: 8080
logging:
root level: DEBUG - Start the application using parameters in the command line.
In the command line, you can set startup parameters in the following format: - Run your application by executing the following command in Java: java -jar your-application.jar –server.port=8080 –logging.level.root=DEBUG.
- Use annotations in the code to set parameters.
By using the @SpringBootApplication annotation on the main class, you can configure common startup parameters such as the port number. - Annotation @SpringBootApplication is used to enable auto-configuration in the application. Excluding certain configurations like DataSourceAutoConfiguration and HibernateJpaAutoConfiguration. This class represents YourApplication, with a main method that runs the SpringApplication with the specified arguments.
- If more precise control over parameters is needed, you can use the @ConfigurationProperties annotation to inject parameters into a custom configuration class.
- The class YourConfigProperties is annotated with @ConfigurationProperties(prefix = “your.config”) and @Component. It contains properties such as property1 and property2, along with their getters and setters.
- Next, in the main class, use the @EnableConfigurationProperties annotation to enable this configuration class.
- @SpringBootApplication enables the main class to be scanned and instantiated by the Spring framework. EnableAutoConfiguration excludes DataSourceAutoConfiguration and HibernateJpaAutoConfiguration from the auto-configuration process. EnableConfigurationProperties connects YourConfigProperties class to the application. The main method of YourApplication class runs the Spring application.
- You can specify attribute values in the following format when setting parameters:
- – The value of your first configuration property is equal to value1, while the value of your second configuration property is 42.
These are some common methods for setting startup parameters, and the specific usage can be adjusted according to actual needs.