Spring-BootSpring-BootHelloWorld

9次阅读

共计 4419 个字符,预计需要花费 12 分钟才能阅读完成。

Spring Boot——入门

spring boot 简化了 spring 的开发,是 J2EE 一站式解决方案。

Spring Boot 的优缺点

优点

  • 快速创建独立运行的服务,与主流框架集成。
  • 使用嵌入式 Serverlet 容器,应用无需达成 war 包。
  • starters 自动依赖与版本控制。
  • 大量的自动配置,简化开发,支持自定义配置。
  • 无需 xml 配置,开箱即用。
  • 准生产环境的运行时应用监控。
  • 云计算的天然集成。

缺点

入门容易,精通难;因为很多事情是 spring boot 自动完成的。

微服务

martin flow《Microservices》

martin flow《微服务》中文翻译

实例讲解

Hello World

  • main 函数所在的 HelloWorld 类
    /**
     * @SpringBootApplication 用来告诉程序这是一个 spring boot 应用
     */
    @SpringBootApplication
    public class Helloworld {public static void main(String[] args) {
            // 启动 Spring 应用
            SpringApplication.run(Helloworld.class, args);
        }
    }
  • controller 类

    @Controller
    public class HelloController {
        @ResponseBody
        @RequestMapping("/hello")
        public String hello(){return "Hello world";}
    }

Pom 文件

<!-- spring boot 所有 spring boot starter 的父项目
    是真正管理 spring boot 应用中所有依赖版本
    是 spring boot 的版本仲裁中心(决定依赖库的版本)以后我们导入依赖默认是不需要写版本的(但是那些没有在父项目中管理的依赖自然是需要声明版本号的)-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>


    <dependencies>
        <!-- 开发 web 应用需要的库 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!-- 将应用打包为 jar 包 -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

Spring Boot 主程序分析

    /**
     * @SpringBootApplication 用来告诉程序这是一个 spring boot 应用
     */
    @SpringBootApplication
    public class Helloworld {public static void main(String[] args) {
            // 启动 Spring 应用
            SpringApplication.run(Helloworld.class, args);
        }
    }

@SpringBootApplication 注解标注在某个类上的时候,说明这个类是 SpringBoot 的主配置类,SpringBoot 就应该运行这个类的 main 方法来启动 SpringBoot 应用。该注解为组合注解,由以下注解组成:

    // 指定该注解可以给一个类型进行注解,比如类、接口、枚举
    @Target(ElementType.TYPE)
    // 注解可以保留到程序运行的时候,它会被加载进入到 JVM 中,所以在程序运行时可以获取到它们。@Retention(RetentionPolicy.RUNTIME)
    // 它的作用是能够将注解中的元素包含到 Javadoc 中去。@Documented
    // 如果一个超类被 @Inherited 注解过的注解进行注解的话,那么如果它的子类没有被任何注解应用的话,那么这个子类就继承了超类的注解。@Inherited
    // 表明这个类是一个 SpringBoot 的配置类
    @SpringBootConfiguration
    // 告诉 SpringBoot 开启自动配置功能,自动配置才会生效
    @EnableAutoConfiguration
    @ComponentScan(excludeFilters = {@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
        @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
    public @interface SpringBootApplication {}

@SpringBootConfiguration 标记在某个类上时,表明这个类是一个 SpringBoot 的配置类。其组成为:

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

​ 其中,@Configuration注解是 Spring 框架中基本的一个注解,在配置类上标记该注解,表明这个类是 Spring 的配置类。

@EnableAutoConfiguration告诉 SpringBoot 开启自动配置功能,这样自动配置才能生效。其组成为:

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Inherited
    @AutoConfigurationPackage
    @Import(AutoConfigurationImportSelector.class)
    public @interface EnableAutoConfiguration {}

​ 其中 @AutoConfigurationPackage自动配置包,将主配置类(即 @SpringBootApplication 标注的类)所在包及其下面所有子包里面的所有组件扫描到 Spring 容器中。其组成为:

        @Import(AutoConfigurationPackages.Registrar.class)
        public @interface AutoConfigurationPackage {}

@Import为 Spring 的底层注解,表明给容器中导入一个组件,导入的组建由 AutoConfigurationPackages.Registrar 类提供。

@Import(AutoConfigurationImportSelector.class) 表明开启自动导入哪些组建的选择器;

​ AutoConfigurationImportSelector.class 将要导入的组件以全类名的方式返回,这些容器会被导入到 Spring 容器。会给容器中导入非常多的自动配置类(一般以 xxxAutoConfiguration 结尾)。这些自动配置类的作用就是给容器中导入场景所需的自动配置,有了自动配置类,就可以不用手动写配置了

自动配置类是怎么找到的呢?

AutoConfigurationImportSelector 
  - selectImports(AnnotationMetadata annotationMetadata) 
    - List<String> configurations = getCandidateConfigurations(annotationMetadata,
                    attributes); // 返回所有配置,对应上面的图
      - List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
        - protected Class<?> getSpringFactoriesLoaderFactoryClass() {return EnableAutoConfiguration.class;}
            - String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
        - Enumeration<URL> urls = classLoader != null?classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
            

从类路径下(如引用的各个 jar 包)的 META-INF/spring.factories 中获取 EnableAutoConfiguration制定的值(自动配置类),这些值作为自动配置类导入到容器中,自动配置类就生效了,帮我们进行自动配置工作。以前我们需要自己配置的类,spring boot 都自动配置了:

spring-boot-autoconfigure包中,包含了 J2EE 所有整合方案和所有自动配置。

org\springframework\boot\spring-boot-autoconfigure\1.5.9.RELEASE\spring-boot-autoconfigure-1.5.9.RELEASE.jar!\org\springframework\boot\autoconfigure

使用 Spring Initializer 快速创建 Spring Boot 项目

  • 首先,需要在 IDEA 中安装 Spring Assisstant 插件。
  • 选择需要的模块,IDEA 会自动 联网 下载 Spring boot 应用模板:
  • resources 文件夹中目录结构:

    • static:保存所有静态资源,如 js、css、images;
    • templates:保存所有的模板页面;(Spring Boot 默认 jar 包使用嵌入式的 Tomcat,默认不支持 jsp 页面);可以使用模板引擎(freemarker,thymeleaf);
    • application.properties:Spring Boot 应用的配置文件,可以修改一些默认设置,如服务的端口号。
正文完
 0