1: springboot features
1. Dependency management
-
The main function of the parent project: dependency management
Dependency management <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.4.RELEASE</version> </parent> he(Parent project of the above dependency management) <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>2.3.4.RELEASE</version> </parent> It declares the version number of almost all dependencies commonly used in development (automatic version arbitration mechanism)
-
Develop and import starter scenario launcher
1,See a lot spring-boot-starter-* : *Represents a scene 2,Just introduce starter,We will automatically introduce all the dependencies required for this scenario 3,SpringBoot All supported scenarios: https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter 4,See *-spring-boot-starter: The third party provides us with a scenario launcher to simplify development. 5,The lowest level dependency of all scenario initiators: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.3.4.RELEASE</version> <scope>compile</scope> </dependency>
-
No need to pay attention to the version number, automatic version arbitration
1,By default, no version can be written when importing dependencies 2,Introducing non version arbitrations jar,To write the version number.
-
You can modify the default version number
1,see spring-boot-dependencies It specifies the current dependent version key. 2,Rewrite the configuration in the current project <properties> <mysql.version>5.1.43</mysql.version> </properties>
2. Automatic configuration
-
Automatically configure Tomcat
-
Introduce Tomcat dependency.
-
Configure Tomcat
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <version>2.3.4.RELEASE</version> <scope>compile</scope> </dependency>
-
-
Automatically configure spring MVC
- Introducing a full set of spring MVC components
- Automatically configure common spring MVC components (functions)
-
Automatically configure common Web functions, such as solving character coding problems, view parser, file upload, etc.
- SpringBoot helps us configure all common scenarios for web development (just introduce initiator dependencies)
-
Default package structure
-
The components in the package where the main program is located and all its sub packages will be scanned by default
-
No previous package scan configuration is required
-
To change the scan path:
@SpringBootApplication(scanBasePackages="com.atguigu") public class MainApplication { ... }
-
Or: @ ComponentScan specifies the scan path
@SpringBootApplication Equivalent to @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan("com.atguigu.boot")
-
-
-
Various configurations have default values
- The default configuration is ultimately mapped to a class, such as MultipartProperties
- The value of the configuration file will eventually be bound to each class, which will create objects in the container
-
Load all auto configuration items on demand
- Very many starter s
- What scenarios are introduced and the automatic configuration of this scenario will be enabled
- All spring boot autoconfigure functions are in the spring boot autoconfigure package
-
...
3. Container function
1. Component addition
@Configuration
Basic use
- Full mode and Lite mode
-
Example
-
Best practice
- There is no dependency between configuration class components. Use Lite mode to accelerate the container startup process and reduce judgment
- Before the Full class is configured, the dependency between components will be obtained by using the Full method
-
###################Configuration Use example############################################## /** * be careful: * 1,The @ Bean annotation is used in the configuration class to register components for the container on the method. By default, it is also single instance * 2,The configuration class itself is also a component * * 3,proxyBeanMethods: Method of proxy bean. There are two modes: * Full: (proxyBeanMethods = true),[How many times each @ Bean method is called and the returned component is single instance] * Lite: (proxyBeanMethods = false)[How many times is each @ Bean method called and the returned component is newly created] * Component dependency (that is, one component uses another component and requires a single instance) must use the Full default mode. Others use Lite mode by default. * * */ @Configuration(proxyBeanMethods = false) //@Configuration: tell SpringBoot that this is a configuration class = = configuration file public class MyConfig { /** * Full:No matter how many external calls are made to the component registration method in the configuration class, the single instance object in the previous registration container is obtained * @return */ @Bean //@Bean: add components to the container. Take the method name as the id of the component. The return type is the component type. The returned value is the instance of the component in the container public User user01(){ User zhangsan = new User("zhangsan", 18); //The user component depends on the Pet component zhangsan.setPet(tomcatPet()); return zhangsan; } @Bean("tom")//Custom component id: tom public Pet tomcatPet(){ return new Pet("tomcat"); } } #########################@Configuration The test code is as follows#################################### @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan("com.atguigu.boot") public class MainApplication { public static void main(String[] args) { //1. Return to our IOC container ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); //2. View the components in the container String[] names = run.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } //3. Get component from container Pet tom01 = run.getBean("tom", Pet.class); Pet tom02 = run.getBean("tom", Pet.class); System.out.println("Components:"+(tom01 == tom02)); //4,com.atguigu.boot.config.MyConfig$$EnhancerBySpringCGLIB$f1e1ca@1654a892 , this instance is a spring enhanced proxy object MyConfig bean = run.getBean(MyConfig.class); System.out.println(bean); //If the @ Configuration(proxyBeanMethods = true) proxy object calls the method. SpringBoot always checks whether the component already exists in the container - > keep the single instance of the component User user = bean.user01(); User user1 = bean.user01(); System.out.println(user == user1); User user01 = run.getBean("user01", User.class); Pet tom = run.getBean("tom", Pet.class); System.out.println("User's pet:"+(user01.getPet() == tom)); } }
@Bean,@Component,@Controller,@Service,@Repository
These previous studies also support! Note that it should be written within the package scanning range!
@ComponentScan,@Import
/** * 4,@Import({User.class, DBHelper.class}) * Location: add to component * Function: automatically create these two types of components in the container. The name of the default component is the full class name * */ //@ComponentScan("com.atguigu.boot") / / package scan @Import({User.class, DBHelper.class}) @Configuration(proxyBeanMethods = false) //Tell SpringBoot that this is a configuration class = = configuration file public class MyConfig { }
@Import advanced usage: https://www.bilibili.com/video/BV1gW411W7wy?p=8
@Conditional
Conditional assembly: if the conditions specified in conditional are met, component injection is performed. (like subclasses, used to specify different conditions)
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Zv7aW8GI-1627625246572)(D: / Notes / typera_images / 1602835786727-28b6f936-62f5-4fd6-a6c5-ae690bd1e31d. PNG)]
=====================Test condition assembly========================== @Configuration(proxyBeanMethods = false) //Tell SpringBoot that this is a configuration class = = configuration file //@ConditionalOnBean(name = "tom") / / indicates that this class takes effect only when there is a tom component in the container. @ConditionalOnMissingBean(name = "tom")//This class takes effect only when there is no tom component in the container. public class MyConfig { /** * Full:No matter how many external calls are made to the component registration method in the configuration class, the single instance object in the previous registration container is obtained * @return */ @Bean //Add components to the container. Take the method name as the id of the component. The return type is the component type. The returned value is the instance of the component in the container public User user01(){ User zhangsan = new User("zhangsan", 18); //The user component depends on the Pet component zhangsan.setPet(tomcatPet()); return zhangsan; } @Bean("tom22") public Pet tomcatPet(){ return new Pet("tomcat"); } } public static void main(String[] args) { //1. Return to our IOC container ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args); //2. View the components in the container String[] names = run.getBeanDefinitionNames(); for (String name : names) { System.out.println(name); } boolean tom = run.containsBean("tom"); System.out.println("In container Tom Components:"+tom); boolean user01 = run.containsBean("user01"); System.out.println("In container user01 Components:"+user01); boolean tom22 = run.containsBean("tom22"); System.out.println("In container tom22 Components:"+tom22); }
2. Native profile import
@ImportResource
======================beans.xml========================= <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd"> <bean id="haha" class="com.atguigu.boot.bean.User"> <property name="name" value="zhangsan"></property> <property name="age" value="18"></property> </bean> <bean id="hehe" class="com.atguigu.boot.bean.Pet"> <property name="name" value="tomcat"></property> </bean> </beans> ===================Import============================= @ImportResource("classpath:beans.xml") //Import the configuration file to make it effective public class MyConfig {} ======================test================= boolean haha = run.containsBean("haha"); boolean hehe = run.containsBean("hehe"); System.out.println("haha: "+haha);//true System.out.println("hehe: "+hehe);//true
3. Configure binding
How to use Java to read the contents of the properties file and package it into JavaBean s for use at any time;
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();//Get the name of the configuration file while(enum1.hasMoreElements()) { String strKey = (String) enum1.nextElement(); String strValue = pps.getProperty(strKey); System.out.println(strKey + "=" + strValue); //Encapsulate into JavaBean s. } } }
@ConfigurationProperties
application.propertites
mycar.brand=BYD mycar.price=100000
/** * Note: only the components in the container can have the powerful functions provided by SpringBoot. */ @Component //@Configuration properties does not bind components to containers, so you need to bind components to containers yourself @ConfigurationProperties(prefix = "mycar") //mycar is the property name in the properties file public class Car { private String brand; private Integer price; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public Integer getPrice() { return price; } public void setPrice(Integer price) { this.price = price; } @Override public String toString() { return "Car{" + "brand='" + brand + '\'' + ", price=" + price + '}'; } }
@EnableConfigurationProperties
Usage scenario: when using externally imported packages, if this class does not have a binding container, it is necessary to enable the configuration binding function of this class.
For example:
@EnableConfigurationProperties(Car.class) /* effect: 1,Enable the Car configuration binding function. Note that the Car uses @ ConfigurationProperties to configure binding 2,Automatically register the Car component into the container */ public class MyConfig { }
2: Introduction to the principle of automatic configuration
1. Boot load automatic configuration class
Annotation of main program class: @ SpringBootApplication
@SpringBootConfiguration @EnableAutoConfiguration @ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) }) public @interface SpringBootApplication{...}
@SpringBootConfiguration
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Configuration public @interface SpringBootConfiguration { @AliasFor( annotation = Configuration.class ) boolean proxyBeanMethods() default true; }
@Configuration. Represents the current configuration class
@ComponentScan
Specify which to scan. (refer to Spring notes)
@EnableAutoConfiguration
... @AutoConfigurationPackage @Import(AutoConfigurationImportSelector.class) public @interface EnableAutoConfiguration {...}
-
@AutoConfigurationPackage
Auto configure package: Specifies the default package rule
@Import(AutoConfigurationPackages.Registrar.class) //Import a component into the container public @interface AutoConfigurationPackage {} //Use the Registrar to import a series of components into the container // =>Import all components under the specified package: under the package of MainApplication.
-
@Import(AutoConfigurationImportSelector.class)
Execution steps: 1,utilize getAutoConfigurationEntry(annotationMetadata);Batch import some components into the container 2,call List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)Get all the configuration classes that need to be imported into the container 3,Using factory loading: Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);Get all the components 4,from META-INF/spring.factories Location to load a file. By default, it scans all of our current systems META-INF/spring.factories Location file spring-boot-autoconfigure-2.3.4.RELEASE.jar It's also in the bag META-INF/spring.factories
-
The 127 configuration classes will be loaded: of course, after loading, the generation will not take effect. It is configured on demand.
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG djfntquv-1627625246574) (D: \ notes \ typora_images/1602845382065-5c41abf5-ee10-4c93-89e4-2a9b831c3ceb.png)]
It's dead in the file spring-boot All configuration classes to be loaded in the container upon startup: Location: spring-boot-autoconfigure-2.3.4.RELEASE.jar/META-INF/spring.factories # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\ org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\ org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\ org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\ org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\ org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\ org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\ org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration,\ org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration,\ org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration,\ org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.elasticsearch.ReactiveElasticsearchRestClientAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jdbc.JdbcRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.ldap.LdapRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoReactiveRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.neo4j.Neo4jRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.r2dbc.R2dbcTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration,\ org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\ org.springframework.boot.autoconfigure.elasticsearch.ElasticsearchRestClientAutoConfiguration,\ org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\ org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\ org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\ org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\ org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\ org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\ org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration,\ org.springframework.boot.autoconfigure.http.codec.CodecsAutoConfiguration,\ org.springframework.boot.autoconfigure.influx.InfluxDbAutoConfiguration,\ org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration,\ org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\ org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JdbcTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\ org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\ org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\ org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\ org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\ org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\ org.springframework.boot.autoconfigure.jsonb.JsonbAutoConfiguration,\ org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration,\ org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.embedded.EmbeddedLdapAutoConfiguration,\ org.springframework.boot.autoconfigure.ldap.LdapAutoConfiguration,\ org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\ org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\ org.springframework.boot.autoconfigure.mongo.MongoReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\ org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\ org.springframework.boot.autoconfigure.quartz.QuartzAutoConfiguration,\ org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketRequesterAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketServerAutoConfiguration,\ org.springframework.boot.autoconfigure.rsocket.RSocketStrategiesAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration,\ org.springframework.boot.autoconfigure.security.servlet.SecurityFilterAutoConfiguration,\ org.springframework.boot.autoconfigure.security.reactive.ReactiveSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.reactive.ReactiveUserDetailsServiceAutoConfiguration,\ org.springframework.boot.autoconfigure.security.rsocket.RSocketSecurityAutoConfiguration,\ org.springframework.boot.autoconfigure.security.saml2.Saml2RelyingPartyAutoConfiguration,\ org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,\ org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.client.servlet.OAuth2ClientAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.client.reactive.ReactiveOAuth2ClientAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.resource.servlet.OAuth2ResourceServerAutoConfiguration,\ org.springframework.boot.autoconfigure.security.oauth2.resource.reactive.ReactiveOAuth2ResourceServerAutoConfiguration,\ org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,\ org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration,\ org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration,\ org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,\ org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,\ org.springframework.boot.autoconfigure.validation.ValidationAutoConfiguration,\ org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration,\ org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.HttpHandlerAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.ReactiveWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.WebFluxAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.error.ErrorWebFluxAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.function.client.ClientHttpConnectorAutoConfiguration,\ org.springframework.boot.autoconfigure.web.reactive.function.client.WebClientAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.reactive.WebSocketReactiveAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration,\ org.springframework.boot.autoconfigure.websocket.servlet.WebSocketMessagingAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.WebServicesAutoConfiguration,\ org.springframework.boot.autoconfigure.webservices.client.WebServiceTemplateAutoConfiguration
-
2. Turn on the automatic configuration item as required
Although all the automatic configurations of our 127 scenarios are loaded by default when they are started. xxxxAutoConfiguration But according to the conditional assembly rules(@Conditional),It will eventually be configured on demand. (add to container as needed)
3. Modify the default configuration
@Bean @ConditionalOnBean(MultipartResolver.class) //There are components of this type in the container @ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME) //There is no component with this name multipartResolver in the container public MultipartResolver multipartResolver(MultipartResolver resolver) { //If the method labeled @ Bean passes in an object parameter, the value of this parameter will be found from the container. //SpringMVC multipartResolver. Prevent the file upload parser configured by some users from not conforming to the specification // Detect if the user has created a MultipartResolver but named it incorrectly return resolver; } This method adds a file upload parser to the container;
Design pattern: SpringBoot will configure all components at the bottom by default. However, if the user has configured it himself, the user's priority shall prevail. Because there is a @ ConditionalOnMissingBean on the default component generation method, SpringBoot will not be configured if it is configured by the user.
Modify the default configuration: write the relevant components and put them in the container. For example:
@Bean @ConditionalOnMissingBean public CharacterEncodingFilter characterEncodingFilter() { }
4. Summary
-
SpringBoot loads all the autoconfiguration classes xxxxconfiguration first
-
Each automatic configuration class takes effect according to conditions, and will bind the value specified in the configuration file by default. Take it from xxproperties. (xxxProperties is bound to the configuration file)
-
The effective configuration class will assemble many components in the container
-
As long as these components are in the container, they are equivalent to these functions
-
Customized configuration:
- Method 1: the user directly replaces the underlying components with @ Bean
- Method 2: the user can modify the value in the configuration file (properties) obtained by the component.
Xxxautoconfiguration (annotation) - > component - > take value from xxxproperties -- (location) - > application properties
Best practices:
How to write SpringBoot:
-
Introduce scenario dependency
- https://docs.spring.io/spring-boot/docs/current/reference/html/using-spring-boot.html#using-boot-starter
-
View which are automatically configured (optional)
- Method 1: analyze by yourself. (the automatic configuration corresponding to the imported scenario generally takes effect)
- Method 2: debug=true in the configuration file: start the automatic configuration report. Negative \ Positive
-
Need to modify
-
Modify configuration items by referencing documents
- https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties
- Analyze yourself. Which of the configuration files are bound by xxproperties.
-
Custom add or replace components (bottom layer: if the user has, the user's priority shall prevail)
- @Bean,@Component......
-
Customizer xxxxxxcustomizer;
-
...
-
Development tips
Lombok
Simplify JavaBean development
Import dependency: <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> idea Search for installation in lombok plug-in unit ===============================simplify JavaBean development=================================== @NoArgsConstructor //@AllArgsConstructor @Data @ToString @EqualsAndHashCode public class User { private String name; private Integer age; private Pet pet; public User(String name,Integer age){ this.name = name; this.age = age; } } ================================Simplified log development=================================== @Slf4j @RestController public class HelloController { @RequestMapping("/hello") public String handle01(@RequestParam("name") String name){ log.info("The request came in...."); return "Hello, Spring Boot 2!"+"Hello:"+name; } }
dev-tools
Import dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
Role: hot deployment. (but this is essentially "restart": when page modification is detected, spring boot will be restarted = = press the restart button)
After the project or page is modified: Ctrl+F9 (recompile the project); It can take effect.
If you want to use real reload, you need to use JRebel paid by idea.
Spring Initailizr (project initialization wizard)
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-KwkSYxIn-1627625246576)(D: \ note \ typera_images / image-2021022212434680. PNG)]
0. Select the development scenario we need
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-1e1nkPEK-1627625246578)(D: \ notes \ typora_images/1602922147241-73fb2496-e795-4b5a-b909-a18c6011a028.png)]
1. Automatic dependency import
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-8bHAepYm-1627625246579)(D: \ notes \ typera_images / 1602921777330-8fc5c198-75da-4ff9-b82c-71ee3fe18af8. PNG)]
2. Automatically create project structure
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-RQAppkcC-1627625246581)(D: \ notes \ typora_images/1602921758313-5099fe18-4c7b-4417-bf6f-2f40b9028296.png)]
3. Automatically write the main configuration class
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Nc9UIApB-1627625246582)(D: \ notes \ typera_images / 1602922039074-79e98aad-8158-4113-a7e7-305b57b0a6bf. PNG)]
[party document]( https://docs.spring.io/spring-boot/docs/2.4.3/reference/html/using-spring-boot.html#using-boot-devtools)
Import dependency:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency>
Role: hot deployment. (but this is essentially "restart": when page modification is detected, spring boot will be restarted = = press the restart button)
After the project or page is modified: Ctrl+F9 (recompile the project); It can take effect.
If you want to use real reload, you need to use JRebel paid by idea.
Initizr project initialization Wizard
[external chain picture transferring... (IMG kwksyxin-1627625246576)]
0. Select the development scenario we need
[external chain picture transferring... (img-1e1nkPEK-1627625246578)]
1. Automatic dependency import
[external chain picture transferring... (img-8bHAepYm-1627625246579)]
2. Automatically create project structure
[external chain picture transferring... (img-RQAppkcC-1627625246581)]
3. Automatically write the main configuration class
[external chain picture transferring... (img-Nc9UIApB-1627625246582)]