Home >Java >javaTutorial >How are configuration properties bound in Spring Boot?
Configuration properties in Spring Boot can be bound to configuration property classes from property sources, including application properties files, environment variables, and command line parameters. Property binding is done through the @ConfigurationProperties annotation. Practical case: Create a configuration attribute class, bind the attribute source, and obtain the configuration attribute.
Binding of configuration properties in Spring Boot
Spring Boot provides a powerful configuration property mechanism, which allows us to Easily bind configuration values to our applications from various sources such as application properties files, environment variables, and command line arguments.
Creation of configuration attribute class
First, we need to create a configuration attribute class to declare the fields and types of the configuration attribute. For example, the following class defines two configuration properties:
@ConfigurationProperties("my.app") public class AppConfig { private String name; private int port; // getter and setter methods }
Property Sources
In Spring Boot, configuration properties can be bound from various property sources. The most common property sources include:
src/main/resources/application.properties
, contains key-value pairs. MY_APP_NAME
etc. --my.app.name=value
etc. Property binding
Spring Boot automatically binds configuration properties from the property source to the configuration property class. This binding is done through the @ConfigurationProperties
annotation.
Practical Case
The following is a practical case showing how to use configuration properties in a Spring Boot application:
@SpringBootApplication public class MyApp { public static void main(String[] args) { SpringApplication.run(MyApp.class, args); AppConfig config = beanFactory.getBean(AppConfig.class); System.out.println("Name: " + config.getName()); System.out.println("Port: " + config.getPort()); } }
In this example , we create a AppConfig
class and declare it as a configuration property class using the @ConfigurationProperties
annotation. Then, we use beanFactory
to get the AppConfig
bean and print the configured property values.
Run this application and provide the application.properties
file:
my.app.name=My Application my.app.port=8080
You should see the output in the console:
Name: My Application Port: 8080
The above is the detailed content of How are configuration properties bound in Spring Boot?. For more information, please follow other related articles on the PHP Chinese website!