spring-boot 学习笔记

官方文档

工程目的

1. 提供快速开发环境,即其已经将各种以来及默认配置搭建好 
2. spring-boot已配置存在的包版本,但其他依赖却很自由 
3. 提供很多功能插件 
4. 基本上不需要代码或者xml配置 
5. 直接运行应用,不需要web容器(方便调试)

最基本项目依赖

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.4.1.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
</dependencies>
添加main方法运行

@RestController
@RequestMapping("example")
@SpringBootApplication@EnableGlobalMethodSecurity
public class App {
    
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    public static void main(String[] args) throws Exception {        
        SpringApplication.run(App.class, args);    
    }
}

打包编译插件

用于将工程项目代码以及所有依赖jar,打包成一个可执行jar包。
这个功能大概也是spring-boot能成为现在倡导微服务架构的重要选择之一。

<build>  
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

配置文件查找路径顺序

1. A /config subdirectory of the current directory.
2. The current directory
3. A classpath /config package
4. The classpath root

控制默认日志级别

java -jar myapp.jar --debug

静态文件路径配置默认

/static (or /public or /resources or /META-INF/resources) 也可以配置设置spring.resources.staticLocations

应该避免使用jsp

支持的模板引擎,路径为src/main/resources/templates,一些容器不支持jsp,Undertow
如果是打包成war可正常运行,但是可执行jar包不可运行

JSP limitations

When running a Spring Boot application that uses an embedded servlet container (and is packaged as an executable archive), there are some limitations in the JSP support.
•   With Tomcat it should work if you use war packaging, i.e. an executable war will work, and will also be deployable to a standard container (not limited to, but including Tomcat). An executable jar will not work because of a hard coded file pattern in Tomcat.
•   With Jetty it should work if you use war packaging, i.e. an executable war will work, and will also be deployable to any standard container.
•   Undertow does not support JSPs.
•   Creating a custom error.jsp page won’t override the default view for error handling, custom error pages should be used instead.

附加功能都能通过spring-boot-starter-*添加

例如在maven仓库搜索

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

实现核心工具类

org.springframework.core.io.support.SpringFactoriesLoader扫描classpath路径下的所有spring.factories文件,并从中查找配置类;
jdk内部提供的SPI 全称为 (Service Provider Interface) 也是使用这种方式;
所有通过此方式加载的类都会以抽象的方式保存,通过MetadataReaderFactory抽象为ClassMetadata, AnnotationMetadata, MethodMetadata

通过ConfigurationClassParser.processImports解析

以EmbeddedServletContainerAutoConfiguration后面分析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容