Automatic configuration

There is a parent in pom.xml

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.4.3</version>
	<relativePath/> <! -- lookup parent from repository -->
</parent>
Copy the code

In addition to spring-boot-starter-parent, there is also a parent: spring-boot-dependencies

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-dependencies</artifactId>
    <version>2.4.3</version>
  </parent>
Copy the code

There are a number of core dependencies. We do not need to specify the version number when importing springboot dependencies because it is already declared in spring-boot-dependencies

starter

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter</artifactId>
      <version>2.4.3</version>
      <scope>compile</scope>
    </dependency>
Copy the code

For springboot startup scenarios, if you import spring-boot-starter-web, it will help you import all the web dependencies you need. What do you need

The main program

// Main program entry
// Labeled as springboot program
@SpringBootApplication
public class SpringBoot01Application {

	public static void main(String[] args) {
		// Start the programSpringApplication.run(SpringBoot01Application.class, args); }}Copy the code

@SpringBootConfiguration

@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {}
Copy the code

In @SpringBootApplication there are two annotations @SpringBootConfiguration and @EnableAutoConfiguration

At @SpringBootConfiguration there is an @Configuration that indicates that this is a Configuration class

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Configuration
public @interface SpringBootConfiguration {}
Copy the code

The @Component in @Configuration indicates that this is a Component

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {}
Copy the code

@enableAutoConfiguration (Automatic configuration)

// @enableAutoConfiguration: automatic configuration annotation
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {}
Copy the code

In @ EnableAutoConfiguration AutoConfigurationPackage and Import two annotations (AutoConfigurationImportSelector. Class)

@AutoConfigurationPackage

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(AutoConfigurationPackages.Registrar.class)
public @interface AutoConfigurationPackage {}
Copy the code

@ Import (AutoConfigurationPackages. The Registrar. Class) automatic Import registration packet for container bulk Import some components

@Import(AutoConfigurationImportSelector.class)

Get you need to import the configuration class List < String > configurations = getCandidateConfigurations (annotationMetadata, attributes); Use the factory to load all required componentsprivate staticMap<String, List<String>> loadSpringFactories(ClassLoader ClassLoader) scans Enumeration<URL> urls = for the component to be loaded by default from meta-INF /spring.factories  classLoader.getResources(FACTORIES_RESOURCE_LOCATION);public static final String FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";
Copy the code

Web static resource import

1. WebMVcAutoConfiguration. There are so a piece of code in Java

@Configuration(proxyBeanMethods = false)
	@Import(EnableWebMvcConfiguration.class)
	@EnableConfigurationProperties({ WebMvcProperties.class, org.springframework.boot.autoconfigure.web.ResourceProperties.class, WebProperties.class })
	@Order(0)
	public static class WebMvcAutoConfigurationAdapter implements WebMvcConfigurer {
Copy the code

Enter the corresponding class by clicking on webMvcProperties.class

@ EnableConfigurationProperties ({WebMvcProperties. Class,...).
Copy the code

found

/** * Path pattern used for static resources. */
	private String staticPathPattern = "/ * *";
Copy the code

Thus the first path for static resource loading is obtained

  1. webjars

In WebMVcAutoConfiguration. There are so a function in Java

@Override
		protected void addResourceHandlers(ResourceHandlerRegistry registry) {
			super.addResourceHandlers(registry);
                        // If a mapping is specified, the default configuration is invalid
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			ServletContext servletContext = getServletContext();
                        // Start loading static resources from classpath:/ meta-INF /resources/webjars/ if there are webjars in the import
			addResourceHandler(registry, "/webjars/**"."classpath:/META-INF/resources/webjars/");
                        / / if there is no import webjars, from this. The resourceProperties. GetStaticLocations () began to load the static resources
			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if(servletContext ! =null) {
					registration.addResourceLocations(newServletContextResource(servletContext, SERVLET_LOCATION)); }}); }Copy the code

So we got a second path for static resource loading: classpath:/ meta-INF /resources/webjars/, and loaded it under /webjars/**

3. There is a paragraph in the code above

addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
Copy the code

The enclosing mvcProperties. GetStaticPathPattern () is to get our first get the path / * *

Get it by clicking getStaticLocations()

public String[] getStaticLocations() {
			return this.staticLocations;
		}
Copy the code

Click staticLocations again to get it

private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
Copy the code

And finally we get

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/"."classpath:/resources/"."classpath:/static/"."classpath:/public/" };
Copy the code

This is the third static resource load path we’ve taken and loaded it under /**

Conclusion:

Map classpath:/ meta-INF /resources/webjars/ to localhost:8080/webjars/

Public static /** resources map to localhost: 8080/

Priority: Resource >static(default)>public

We can change the default address by spring.mvc. Static-path-pattern = /hello/**,classpath:/line/

Home page

WebMVcAutoConfiguration. There was a piece of code in Java

private Resource getWelcomePage(a) {
                        // Iterate through the static resource directory
			for (String location : this.resourceProperties.getStaticLocations()) {
				Resource indexHtml = getIndexHtml(location);
				// Successfully retrieved index.html and returned
                                if(indexHtml ! =null) {
					return indexHtml;
				}
			}
			ServletContext servletContext = getServletContext();
			if(servletContext ! =null) {
				return getIndexHtml(new ServletContextResource(servletContext, SERVLET_LOCATION));
			}
			return null;
		}

Copy the code