SpringBoot
谈谈对springboot的理解
1: 自动配置
SpringBoot启动后从类路径下的META-INF/spring.factories获取EnableAutoConfiguration的指定的值。
这些指定的值作为自动配置类,导入容器,自动配置类生效,完成自动配置工作
2:run方法
推断应用的类型是普通的项目还是Web项目
查找并加载所有可用初始化器 , 设置到initializers属性中
找出所有的应用程序监听器,设置到listeners属性中
推断并设置main方法的定义类,找到运行的主类
1. web开发
1.1 静态资源目录
public void addResourceHandlers(ResourceHandlerRegistry registry) {
if (!this.resourceProperties.isAddMappings()) {
logger.debug("Default resource handling disabled");
return;
}
addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
registration.addResourceLocations(this.resourceProperties.getStaticLocations());
if (this.servletContext != null) {
ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
registration.addResourceLocations(resource);
}
});
}
从getStaticLocations进去
可以发现,读取的静态目录包括以下几个:
也就是说放在这几个下面的js文件都可以被读到
yaml里配置
spring:
mvc:
static-path-pattern:
1.2 首页配置
private Resource getIndexHtml(String location) {
return getIndexHtml(this.resourceLoader.getResource(location));
}
private Resource getIndexHtml(Resource location) {
try {
Resource resource = location.createRelative("index.html");
if (resource.exists() && (resource.getURL() != null)) {
return resource;
}
}
catch (Exception ex) {
}
return null;
}
寻找index.html
如果要将index文件放入到templates,
- 必须要controller来跳转,
- 需要模板引擎的支持 需要temymeleaf依赖
1.3 模板引擎
2. 一个简单的项目
pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
password:
username: root
url:
server:
port: 8080
#spring:
# mvc:
# static-path-pattern:
---
server:
port: 8081
spring:
profiles:
active: test #控制端口
---
server:
port: 8082
spring:
profiles: dev
---
server:
port: 8083
spring:
profiles: test
---