Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the automatic configuration principle of SpringBoot 05?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

What is the principle of SpringBoot 05 automatic configuration? in view of this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and easy way.

Automatic configuration principle

What on earth can the configuration file write? How to write? There are a large number of configurations in the SpringBoot official documentation, we can not remember all of them, just find the exact location on the official website. The question is how does it come true at the bottom? we need to figure it out.

Analyze the principle of automatic configuration

We take HttpEncodingAutoConfiguration (Http coding automatic configuration) as an example to explain the principle of automatic configuration.

/ / indicates that this is a configuration class, and like the previously written configuration file, you can also add components to the container; @ Configuration / / start the ConfigurationProperties function of the specified class; / / check the HttpProperties and bind the corresponding values in the configuration file to HttpProperties / / and add HttpProperties to the ioc container @ EnableConfigurationProperties ({HttpProperties.class}) / / Spring underlying @ Conditional comment / / according to different conditions, if the specified conditions are met, the configuration in the entire configuration class will take effect; / / this means to determine whether the current application is a web application, and if so, the current configuration class takes effect @ ConditionalOnWebApplication (type = Type.SERVLET) / / to determine whether the current project has this type of CharacterEncodingFilter. Filter for garbled resolution in SpringMVC; @ ConditionalOnClass ({CharacterEncodingFilter.class}) / / determine whether a certain configuration exists in the configuration file: spring.http.encoding.enabled; / / if it does not exist, the judgment is valid / / even if we do not configure pring.http.encoding.enabled=true in the configuration file, it will take effect by default @ ConditionalOnProperty (prefix = "spring.http.encoding", value = {"enabled"}, matchIfMissing = true) public class HttpEncodingAutoConfiguration {/ / he has mapped private final Encoding properties; with SpringBoot's configuration file / / if there is only one parameter constructor, the value of the parameter will be taken from the container public HttpEncodingAutoConfiguration (HttpProperties properties) {this.properties = properties.getEncoding () } / / add a component to the container. Some values of this component need to be obtained from properties @ Bean @ ConditionalOnMissingBean / / to determine that the container does not have this component? Public CharacterEncodingFilter characterEncodingFilter () {CharacterEncodingFilter filter = new OrderedCharacterEncodingFilter (); filter.setEncoding (this.properties.getCharset (). Name ()); filter.setForceRequestEncoding (this.properties.shouldForce (org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.REQUEST)); filter.setForceResponseEncoding (this.properties.shouldForce (org.springframework.boot.autoconfigure.http.HttpProperties.Encoding.Type.RESPONSE)); return filter;} / /. } @ EnableConfigurationProperties comment

Let's talk about the function first:

The @ EnableConfigurationProperties annotation is used to validate classes that use the @ ConfigurationProperties annotation.

Description:

If a configuration class only configures the @ ConfigurationProperties annotation and does not use @ Component, then the bean converted by the properties configuration file cannot be obtained in the IOC container. To put it bluntly, @ EnableConfigurationProperties is equivalent to an injection of a class that uses @ ConfigurationProperties.

The test found that @ ConfigurationProperties has a lot to do with @ EnableConfigurationProperties.

The test proves the relationship between @ ConfigurationProperties and @ EnableConfigurationProperties.

The @ EnableConfigurationProperties document explains:

When the @ EnableConfigurationProperties annotation is applied to your @ Configuration, any beans annotated by @ ConfigurationProperties will be automatically configured by the Environment attribute. This style of configuration is particularly suitable for use with SpringApplication's external YAML configuration.

The test found:

1. Use @ EnableConfigurationProperties to register

ConfigurationProperties (prefix = "service.properties") public class HelloServiceProperties {private static final String SERVICE_NAME = "test-service"; private String msg = SERVICE_NAME; set/get} @ Configuration@EnableConfigurationProperties (HelloServiceProperties.class) @ ConditionalOnClass (HelloService.class) @ ConditionalOnProperty (prefix = "hello", value = "enable", matchIfMissing = true) public class HelloServiceAutoConfiguration {} @ RestControllerpublic class ConfigurationPropertiesController {@ Autowired private HelloServiceProperties helloServiceProperties @ RequestMapping ("/ getObjectProperties") public Object getObjectProperties () {System.out.println (helloServiceProperties.getMsg ()); return myConfigTest.getProperties ();}} automatic configuration settings service.properties.name=my-test-nameservice.properties.ip=192.168.1.1service.user=kayleservice.port=8080

Everything is fine, but the @ EnableConfigurationProperties is not used in the HelloServiceAutoConfiguration header and an error is reported in the test access.

two。 Do not register with @ EnableConfigurationProperties, register with @ Component

ConfigurationProperties (prefix = "service.properties") @ Componentpublic class HelloServiceProperties {private static final String SERVICE_NAME = "test-service"; private String msg = SERVICE_NAME; public String getMsg () {return msg;} public void setMsg (String msg) {this.msg = msg;}}

Controller does not change, everything is normal, if comment out @ Component test start error.

This proves that in both ways, classes modified by @ ConfigurationProperties are loaded into Spring Env.

In a word, summarize the principle of configuration:

According to the current different conditions, determine whether this configuration class is effective or not!

As soon as this configuration class takes effect; it adds various components to the container

The properties of these components are obtained from the corresponding properties classes, and each property in these classes is bound to the configuration file

All properties that can be configured in the configuration file are encapsulated in the xxxxProperties class

What the configuration file can configure, you can refer to the property class corresponding to a function.

/ / get the specified value from the configuration file and bind the properties of bean to @ ConfigurationProperties (prefix = "spring.http") public class HttpProperties {/ /.}

Let's try the prefix in the configuration file and see the hint!

This is the principle of automatic assembly!

Essence

1. SpringBoot startup will load a large number of automatic configuration classes

2. Let's see if the functions we need are in the automatic configuration class written by SpringBoot by default.

3. Let's take a look at which components are configured in this automatic configuration class. (as long as the components we want to use exist in them, we no longer need to configure them manually.)

4. When you add components to the automatic configuration class in the container, you will get some properties from the properties class. We only need to specify the values of these properties in the configuration file

5. XxxxAutoConfigurartion: automatically configure classes; add components to the container

6. XxxxProperties: encapsulate the relevant attributes in the configuration file

@ Conditional

After understanding the principle of automatic assembly, let's pay attention to a detail. The automatic configuration class can only take effect under certain conditions.

@ Conditional derived comments (the native @ Conditional function of the Spring annotated version)

Function: the condition specified by @ Conditional must be established to add components to the container, and all the contents of the configuration will take effect.

So many automatic configuration classes must take effect under certain conditions; that is, we have loaded so many configuration classes, but not all of them have taken effect.

How do we know which autoconfiguration classes are in effect?

We can make the console print the automatic configuration report by enabling the debug=true property, so that we can easily know which automatic configuration classes are in effect.

# enable debug class debug=true==CONDITIONS EVALUATION REPORT==Positive matches of springboot: (auto configuration class enabled: exact match)-AopAutoConfiguration matched:-@ ConditionalOnProperty (spring.aop.auto=true) matched (OnPropertyCondition)... Negative matches: (not started No successful autoconfiguration classes: negative matching)-ActiveMQAutoConfiguration: Did not match:-@ ConditionalOnClass did not find required class' javax.jms.ConnectionFactory' (OnClassCondition) .exclusions:-NoneUnconditional classes: (classes without conditions)- -this is the answer to org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration 's question about the principle of automatic configuration of SpringBoot 05. I hope the above content can help you to a certain extent, if you still have a lot of doubts to be solved, you can follow the industry information channel to learn more related knowledge.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report