search
HomeJavajavaTutorialHow SpringBoot2 underlying annotation @ConfigurationProperties configures binding

We usually put some frequently changed things into the configuration file.

For example, the port number server.port=8080 previously written in the configuration file application.properties, and other common ones include database connection information, etc.

Then, my database connection information is placed in the configuration file. If I want to use it, I must parse the configuration file and use the parsed content in the bean.

The whole scenario is actually binding all the configurations in the configuration file to the java bean.

To complete this scenario, it is still a bit troublesome to write based on java native code. Usually, an encapsulation is made to read the contents of the properties file and encapsulate it into a JavaBean:

public class getProperties {     public static void main(String[] args) throws FileNotFoundException, IOException {         Properties pps = new Properties();         pps.load(new FileInputStream("a.properties"));         Enumeration enum1 = pps.propertyNames();//得到配置文件的名字         while(enum1.hasMoreElements()) {             String strKey = (String) enum1.nextElement();             String strValue = pps.getProperty(strKey);             System.out.println(strKey + "=" + strValue);             //封装到JavaBean             ... ...         }     }

Here, the Properties class is used to load the configuration filea. properties, and then traverse each k-v in the configuration file. After obtaining it, you can use it in the corresponding place.

This process is simplified in springboot, which is configuration binding.

Configuration binding

Configuration binding is completed by using the annotation @ConfigurationProperties. Note that it needs to be used in conjunction with @Component.

Create a new component Car, with two properties: brand and price:

@Componentpublic class Car {    private String brand;    private Integer price;// get set tostring 就不贴了

In the configuration file application.properties, set some properties Value, for example:

mycar.brand=QQmycar.price=9999

Use @ConfigurationProperties annotation and add it to the component:

@Component@ConfigurationProperties(prefix = "mycar")public class Car {    private String brand;    private Integer price;... ...

The prefix passed in is the prefix in the configuration file, here is mycar.

Verification

Now let’s test whether the binding is successful. Continue to add a controller method in the previous HelloController:

@RestControllerpublic class HelloController {    @Autowired    Car car;    @RequestMapping("/car")    public Car car() {        return car;    }    @RequestMapping("/hello")    public String Hello() {        return "Hello SpringBoot2 你好";    }}

Deploy the application, The browser accesses http://localhost:8080/car:

How SpringBoot2 underlying annotation @ConfigurationProperties configures binding

and the binding is successful.

Another way

In addition to the above method, you can also use @EnableConfigurationProperties @ConfigurationProperties to complete the binding.

Note that the @EnableConfigurationProperties annotation should be used on the configuration class to indicate the function of enabling property configuration:

//@ConditionalOnBean(name = "pet1")@Import({User.class, DBHelper.class})@Configuration(proxyBeanMethods = true)@ImportResource("classpath:beans.xml")  //配置文件的类路径@EnableConfigurationProperties(Car.class) //开启属性配置的功能public class MyConfig {    @Bean("user1")    public User user01(){        User pingguo = new User("pingguo",20);        pingguo.setPet(tomcatPet());        return pingguo;    }    @Bean("pet22")    public Pet tomcatPet(){        return new Pet("tomcat");    }}

@EnableConfigurationProperties(Car.class)Pass in the class to enable configuration, which can automatically register the Car into the container, which means that the @Component on the previous Car is no longer needed.

//@Component@ConfigurationProperties(prefix = "mycar")public class Car {    private String brand;    private Integer price;

Re-deploy and access the next address, it still works.

How SpringBoot2 underlying annotation @ConfigurationProperties configures binding

Regarding the second usage scenario, for example, the Car here is a class in a third-party package, but the source code does not have the @Component annotation. , then you can bind in this way.

Finally, remember that when using @ConfigurationProperties(prefix = "mycar") this configuration is bound to the springboot core configuration file application.properties file The binding relationship established by the content.

The above is the detailed content of How SpringBoot2 underlying annotation @ConfigurationProperties configures binding. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software