What is Spring Boot
Spring Boot is basically an extension of the Spring framework that eliminates the complex routine configuration required to set up a Spring application. When we use the Spring framework, we should be more exposed to Spring MVC, IOC, DI, AOP and so on, and these frameworks will need to configure a lot of XML in the process of using, or need to do a lot of tedious configuration. Spring Boot can help us quickly build an application solution based on the Spirng framework and the Spring ecosystem.
- Create a stand-alone Spring application
- Java -JAR can be run by embedding Tomcat, Jetty, or Undertow directly (without deploying a WAR file)
- Provide starter dependencies to simplify your own configuration
- Autowire Spring and third-party dependencies whenever possible
- Provides productionable functions such as metrics, health checks, and externalization configurations such as Actuator
- No code generation at all and no XML configuration is required
There are two main points in looking at all of this, conventions outweigh configuration and autoassemble.
Convention over configuration
Convention over configuration is mainly reflected in
- Maven’s directory structure, by default, contains configuration files in the Resources folder and is packaged in jars by default
- Spring-boot-starter – Web includes spring MVC dependencies and a built-in Tomcat container by default, making building a Web application easier
- Provide application by default. The properties/yml file
- By default, the spring.profiles. Active property determines which configuration files are read at runtime
- EnableAutoConfiguration Automatically assembles the dependent starter by default
Automatically.
We’ll start with the annotation, we’ll go to @springBootApplication
- @Configuration
- @EnableAutoConfiguration
- @ComponentScan
You can use the three annotations directly or launch the Spring Boot application, but configuring three annotations at a time is tedious, so it’s easier to just use one composite annotation. Below is a screenshot of the official website, and you can translate it by yourself.
@Configuration
The @configuration annotation, which you’ve probably used before, is an annotation used by the JavaConfig form of the Spring IOC container-based Configuration class. So the @Configuration label in the startup class means that it is also an IoC container Configuration class.
Traditional Spring applications have configured bean dependencies in XML form. However, since Spring3, Spring has supported two types of bean configuration, one based on XML file and the other on JavaConfig. Any Java class definition labeled @Configuration is a JavaConfig Configuration class. In this configuration class, the return value of any method labeled @bean is registered with Spring’s IoC container as the Bean definition, and the method name defaults to the id of the Bean. The beans are then initialized at startup by the Spring container and, if there are dependencies between the beans, the beans already in the IoC container are analyzed and assembled according to the dependencies.
@ComponentScan
< context: ComponentScan > < context: ComponentScan > < context: ComponentScan > < context: ComponentScan > Its main function is to scan the identified classes in the specified path and automatically assemble them into Spring’s IoC container.
The main forms of identifying the classes to be assembled are: @Component, @repository, @Service, @Controller, and so on. (Note: @repository, @Service, and @Controller are still underlying @Component). By default, ComponentScan will scan all annotated classes in the current package into the IoC container.
@EnableAutoConfiguration
Ok, here we go. @enableAutoConfiguration is the heart and soul of Spring Boot. Starting with Spring3.1, a series of @enable annotations is provided, which is a further refinement of the JavaConfig framework and makes it easier for users to use spring-related frameworks without having to configure a lot of code.
For example, some common Enable annotations: @enablewebMVC, @enablescheduling, @enableAsync and so on. Every annotation that starts with Enable has an @import annotation, and @enableAutoConfiguration is no exception, as shown in the red box.
- Regular beans or a Configuration file with @Configuration
- Implement the ImportSelector interface for dynamic injection
- Implement ImportBeanDefinitionRegistrar interface for dynamic injection
Import is the second importSelector here, this is a kind of dynamic injection Bean technology, we put the AutoConfigurationImportSelector point in, found it implements importSelector interface.
@Override
public String[] selectImports(AnnotationMetadata annotationMetadata) {
if(! isEnabled(annotationMetadata)) {return NO_IMPORTS;
}
AutoConfigurationMetadata autoConfigurationMetadata = AutoConfigurationMetadataLoader
.loadMetadata(this.beanClassLoader);
AutoConfigurationEntry autoConfigurationEntry = getAutoConfigurationEntry(autoConfigurationMetadata,
annotationMetadata);
return StringUtils.toStringArray(autoConfigurationEntry.getConfigurations());
}
Copy the code
Again from getAutoConfigurationEntry approach, it made a lot of things, is to find the beans to exclude, filtering, heavy, we can see removeDuplicates, remove, filter, etc.
But But
Conditions | describe |
---|---|
@ConditionalOnBean | When a bean exists |
@ConditionalOnMissingBean | When a bean does not exist |
@ConditionalOnClass | When the current CLASspath can find a class of a certain type |
@ConditionalOnMissingClass | When the classpath cannot find a class of a certain type |
@ConditionalOnResource | Whether a resource file exists on the classpath |
@ConditionalOnProperty | Whether the current JVM contains a system property as a value |
@ConditionalOnWebApplication | Whether the current Spring Context is a Web application |
Well, with so much preparatory knowledge above, we can start writing a starter of our own.
Write a starter
Starter project name
Starter is an out-of-the-box component that reduces unnecessary duplication of code and configuration. For example, if you want to use Spring and JPA for database access, just reference spring-boot-starter- data-jPA in your project.
The official Spring starter is named in the format of spring-boot-starter-{name}, for example, spring-boot-starter-web. An unofficial starter must be named in {name}-spring-boot-starter format, for example, dubbo-spring-boot-starter.
demand
Write a serialized plug-in, and feel free to choose between FastJSON and gson. If not, choose fastJSON by default.
steps
Create a Spring Boot project called jackformat-spring-boot-starter
2. Introduce dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-autoconfigure</artifactId> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> < version > 1.2.56 < / version > < / dependency > < the dependency > < groupId > com. Google. Code. Gson < / groupId > < artifactId > gson < / artifactId > < version > 2.2.4 < / version > < / dependency >Copy the code
Define a formatted interface and write two implementation classes separately
Public interface FormatProcessor {/** * Define a format method ** @param obj * @param <T> * @return
*/
<T> String format(T obj);
}
Copy the code
test
1. Package your starter project install
Write a controller, a test class, and inject the formtem plate into it
4, we need to set the serialization method, here select fastJSON
Afterword.
I started using SSM when I graduated from college in 2014. At that time, all kinds of configurations and dependencies and ALL kinds of XML were disgusting. But now there is a Spring Boot in a few minutes can let us build a project quickly run up, The Times change, thank you also let us more and more convenient, in the process of convenience, we still need to understanding of the underlying principle is a bit, rather than floating above can only use, otherwise one but there is a problem is not easy for you to find.
This article takes you to Spring Boot bottom into a door, and SringApplication instance creation, set initializer and listener, as well as some things to do in the run method, how to implement the built-in Tomcat, due to the limited space are not said, left to small partners to study. Finally, the original is not easy, if you think it is good, please click a like!