自动配置原理
在我们配置文件中能配置的东西,都存在一个固有的规律
xxxAutoConfiguration类(在spring.factories)都是容器中的一个组件,最后加入到容器中,用他们来事项自动配置 ; xxxProperties 的 (@ConfiguretionProperties) 和 配置文件 绑定,我们就可以使用自定义的配置了
例子
server:
port: 8081
在SpringBoot中存在一个ServerProperties类,并且这个类是经过一个自动装配,此类会有@ConfiguretionProperties修饰,并且prefix=server,通过这样的方式就会将SpringBoot和配置文件进行一个连接,同时我们也可以在配置文件中对类中的属性进行操作
!!!自动装配原理
- SpringBoot启动时会加载大量的自动配置类(xxxAutoConfiguration)
- 看我们需要的供功能有没有在SpringBoot默认的自动配置类中写好
- 我们再来看自动配置类中到底配置了哪些组件(如果没有,需要我们手动配置)
- 给容器中自动配置类添加组件时,会从xxxProperties中获取某些属性,我们只需要在配置文件中写好对这些数组的值即可
@Conditional指定的条件成立,才给容器中添加该组件,配置文件中的内容才会生效
虽然说SpringBoot中导入了大量的自动配置类,但是这些类并不是全部生效,应该和你创建项目时勾选的东西有关(比如勾选了web,那与web相关的自动配置类肯定会生效),如果在后期想要使用,引入相关的依赖,对应的自动配置类应该就可以生效了
可以通过debug:true来看哪些自动配置类生效了
SpringBoot Web开发
静态资源导入
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {//如果自定义了就会失效
logger.debug("Default resource handling disabled");
} else {
this.addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");//第一中可以获得静态资源的方法
this.addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());//第二中可以获得静态资源的方法
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, "/");
registration.addResourceLocations(new Resource[]{resource});
}
});
}
}
自定义
spring:
mvc:
static-path-pattern: /wjq/**
第一种获取web资源的方式
什么是webjars? 类似于我们导入的maven依赖,将webjars导入,其路径就是可以满足这个条件/META-INF/resources/webjars/
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.6.0</version>
</dependency>
访问静态资源jquery.js,其路径http://localhost:8080/webjars/jquery/3.6.0/jquery.js
第二种获取web资源的方式
this.staticPathPattern = "/**";
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
优先级:resources、static、public
对于首页而言,在resources、static、public目录下,创建index.html即可实现跳转