关于springboot:Spring-Boot-系统学习

2次阅读

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

Spring 框架发展史

Spring1.x 时代

​ 在 Spring1.x 时代,都是通过 xml 文件配置 bean,随着我的项目的不断扩大,须要将 xml 配置分放到不同的配置文件中,须要频繁的在 java 类和 xml 配置文件中切换。

Spring2.x 时代

​ 随着 JDK 1.5 带来的注解反对,Spring2.x 能够应用注解对 Bean 进行申明和注入,大大的缩小了 xml 配置文件,同时也大大简化了我的项目的开发。

那么,问题来了,到底是应该应用 xml 还是注解呢?

最佳实际:

  1. 利用的根本配置用 xml,比方:数据源、资源文件等;
  2. 业务开发用注解,比方:Service 中注入 bean 等;

Spring3.x 到 Spring4.x 再到 Spring5.x

​ 从 Spring3.x 开始提供了 Java 配置形式,应用 Java 配置形式能够更好的了解你配置的 Bean,当初咱们就处于这个时代,并且 Spring4.x、Spring5.x 和 Spring Boot 都举荐应用 java 配置的形式。

Spring 5.X 利用零配置开发

​ Spring 框架从 5.x 版本举荐应用注解模式来对 java 应用程序进行开发与配置, 并且能够齐全代替原始的 XML+ 注解模式的开发, 在应用注解模式进行我的项目开发与环境配置时,Spring 框架提供了针对环境配置与业务 bean 开发相干注解。

注解

申明 Bean 注解

@Component: 组件 没有明确规定其角色,作用在类级别上申明以后类为一个业务组件,被 Spring Ioc 容器保护;

@Service: 在业务逻辑层(Service 层)类级别进行申明;

@Repository: 在数据拜访层(dao 层) 类级别申明;

@Controller: 在展示层(MVC) 应用 标注以后类为一个控制器

注入 Bean 注解

@AutoWired:Spring 官网提供注解

@Inject:JSR-330 提供注解(规范制订方)@Resource:JSR-250 提供注解

​ 以上三种注解在 Set 办法或属性上申明,个别状况下通用个别开发中更习惯申明在属性上,代码简洁清晰。基于 5.x 注解配置形式简化了 xml 配置,利用程序开发与 xml 环境配置均通过相应注解来实现。

Spring5.x 中配置与获取 Bean 注解

 @Configuration: 作用与类上,将以后类申明为一个配置类,相当于一个 xml 配置文件
 @ComponentScan: 主动扫描指定包下标注有 @Repository,@Service,@Controller
 @Component: 注解的类并由 Ioc 容器进行实例化和保护
 @Bean:: 作用于办法上, 相当于 xml 文件中 <bean> 申明以后办法返回值为一个 bean
 @Value: 获取 properties 文件指定 key value 值 

实例 1 -Ioc 中 Bean 的实例化与获取

创立 Spring 一般工程并增加坐标相干配置

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>utf-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>

增加源代码

创立 UserDao ,UserService Bean 对象
// UserDao.java
@Repository
public class UserDao {public  void test(){System.out.println("UserDao.test...");
    }
}


// UserService.java
@Service
public class UserService {
    @Resource
    private UserDao userDao;

    public  void test(){System.out.println("UserService.test...");
        userDao.test();}
}
创立 IocConfig 配置类
// Ioc 容器配置 Java 代码实现
@Configuration
@ComponentScan("com.xxxx.springboot")
public class IocConfig {}
创立启动类执行测试
public class Starter {public static void main(String[] args) {AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(IocConfig.class);
        UserService userService= ac.getBean(UserService.class);
        userService.test();}
}

​ 此时启动 Spring Ioc 容器通过实例化 AnnotationConfigApplicationContext 类,接管配置参数类 IocConfig, 并获取 UserService Bean 实现办法调用, 此时应用环境不存在 xml 配置文件,简化了利用的 xml 配置。

应用 @Bean 注解申明在办法 (留神: 办法名个别为 bean 对象名称) 级别用于返回实例化的 Bean 对象。

@Bean 注解应用

定义 AccountDao 对象, 并交给 Spring Ioc 容器进行实例化

// 留神 此时类级别并未增加 @Repository 注解
public class AccountDao {public  void test(){System.out.println("AccountDao.test...");
    }
}

批改 IocConfig 配置类中增加返回 AccountDao Bean 对象办法

@Configuration
@ComponentScan("com.xxxx.springboot")
public class IocConfig {

    // 返回实例化的单例 Bean 对象
    @Bean
    public AccountDao accountDao(){return new AccountDao();
    }
}

UserService 中注入 AccountDao 对象

@Service
public class UserService {
    @Resource
    private UserDao userDao;

    @Resource
    private AccountDao accountDao;

    public  void test(){System.out.println("UserService.test...");
        userDao.test();
        accountDao.test();}
}

执行测试

public class Starter {public static void main(String[] args) {AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(IocConfig.class);
        UserService userService= ac.getBean(UserService.class);
        userService.test();
        System.out.println(ac.isSingleton("accountDao"));
    }
}

实例 2 - 读取内部配置文件

​ 在开发 Java web 利用进行时, 配置文件是比拟常见的,比方 xml,properties,yml 等文件,在 Spring 利用中对于配置文件的读取同样提供反对。对于配置文件读取,咱们能够通过 @PropertySource 注解申明到类级别来指定读取相干配置配置。

​ Spring El 表达式语言,反对在 Xml 和注解中应用表达式,相似于 JSP 中 EL 表达式,Spring 框架在借助该表达式实现资源注入,次要通过 @Value 注解来应用表达式,通过 @Value 注解,能够实现一般字符串,表达式运算后果,Bean 属性文件内容,属性文件等参数注入。具体应用如下:

筹备 properties 配置文件

src/main/resources 目录下增加 user.properties jdbc.roperties 文件

# user.properties
user.userName=admin
user.password=admin

# jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=root

@PropertySource 加载 properties 配置文件

@Configuration
@ComponentScan("com.shsxt")
@PropertySource(value = {"classpath:jdbc.properties","classpath:user.properties"})
public class IocConfig {@Value("${jdbc.driver}")
    private String url;
    @Value("${jdbc.url}")
    private String driver;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;
    @Bean
    public AccountDao accountDao(){return new AccountDao();
    }
    // 控制台打印属性值信息
    public  void showConfigInfo(){System.out.println("driver:"+driver+":url:"+url);
        System.out.println(":userName:"+userName+":password:"+password);
    }
}

其余 Bean 对象获取 properties 文件内容

@Service
public class UserService {
    @Resource
    private UserDao userDao;

    @Resource
    private AccountDao accountDao;

    @Value("${user.userName}")
    private String userName;
    @Value("${user.password}")
    private String password;

    public  void test(){System.out.println("UserService.test...");
        userDao.test();
        accountDao.test();
        System.out.println("userName:"+userName+":password:"+password);
    }
}

启动 Starter 查看控制台输入内容成果

组合注解与元注解

​ Spring 从 2.x 版本开始引入注解反对(目标是 jdk1.5 中推出注解性能), 通过引入注解来打消大量 xml 配置,Spring 引入注解次要用来注入 bean 以及 aop 切面相干配置, 但因为注解大量应用,就会造成大量反复注解代码呈现,代码呈现了反复,Spring 为了打消反复注解,在元注解上引入了组合注解,其实能够了解为对代码的重构,相当于注解的注解,领有元注解的原始性能,比方在定义配置类时用到的 @Configuration 注解就是组合注解,领有 Component 注解性能,即配置类自身也是一个被 Ioc 保护的单例 Bean。

自定义组合注解

  • 定义 MyCompScan 注解,领有 @ComponentScan 扫描器注解性能
/**
 * 组合注解 MyCompScan 定义
 *    领有元注解 @Configuration + @ComponentScan 两者性能
 *    笼罩 value 属性
 */
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Configuration
@ComponentScan
public @interface MyCompScan {String[] value() default {};
}

利用组合注解

@MyCompScan("com.xxxx.springboot")
@PropertySource(value = {"classpath:jdbc.properties","classpath:user.properties"})
public class IocConfig02 {@Value("${jdbc.driver}")
    private String url;
    @Value("${jdbc.url}")
    private String driver;
    @Value("${jdbc.username}")
    private String userName;
    @Value("${jdbc.password}")
    private String password;
    @Bean
    public AccountDao accountDao(){return new AccountDao();
    }
    
    public  void showConfigInfo(){System.out.println("driver:"+driver+":url:"+url);
        System.out.println(":userName:"+userName+":password:"+password);
    }
}

测试组合注解

public class Starter {public static void main(String[] args) {AnnotationConfigApplicationContext ac=new AnnotationConfigApplicationContext(IocConfig02.class);
        UserService userService= ac.getBean(UserService.class);
        userService.test();
        System.out.println(ac.isSingleton("accountDao"));
        IocConfig iocConfig=ac.getBean(IocConfig.class);
        iocConfig.showConfigInfo();}
}

Spring MVC 零配置创立与部署

​ 基于 Spring Mvc 5.X 应用 Maven 搭建 SpringMvc Web 我的项目, 通过 Spring 提供的注解与相干配置来对我的项目进行创立与部署。

创立 Spring Mvc Web 工程

pom.xml 增加坐标相干配置

   <!-- spring web -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-web</artifactId>
  <version>5.2.3.RELEASE</version>
</dependency>

<!-- spring mvc -->
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.3.RELEASE</version>
</dependency>

<!-- web servlet -->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
</dependency>

<build>
<finalName>springmvc</finalName>
<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>2.3.2</version>
    <configuration>
      <source>1.8</source>
      <target>1.8</target>
      <encoding>utf-8</encoding>
    </configuration>
  </plugin>
    <plugin>
        <groupId>org.eclipse.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>9.4.27.v20200227</version>
      </plugin>
</plugins>
</build>

增加源代码

@Controller
public class HelloController {@RequestMapping("/index")
    public  String index(){return "index";}
}

增加视图

在 WEB-INF/views 目录下创立 index.jsp(这里以 jsp 为模板)

<html>
<body>
<h2>test web mvc</h2>
</body>
</html>

SpringMvc 配置类增加

​ Spring Mvc 配置信息 MvcConfig 文件增加, 作为 Mvc 框架环境,原来是通过 xml 来进行配置(视图解析器,Json 转换器,文件上传解析器等),这里基于注解通过继承 WebMvcConfigurerAdapter 类 并重写相干办法来进行配置(留神通过 @EnableWebMvc 注解来启动 MVC 环境)。

/**
 * mvc 根本配置
 */
@Configuration
@EnableWebMvc
@ComponentScan("com.xxxx.springboot")
public class MvcConfig{


    @Bean
    public InternalResourceViewResolver viewResolver(){InternalResourceViewResolver viewResolver=new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        return viewResolver;
    }
}

​ MvcConfig 类定义好了,那么问题来了,怎么加载 MvcConfig 类呢,原来在构建 Mvc 利用时是通过容器启动利用时加载 web.xml 文件 实现配置文件加载,当初的环境 web.xml 文件不存在,此时基于注解形式构建的 Mvc 利用,定义 WebInitializer 实现 WebApplicationInitializer 接口(该接口用来配置 Servlet3.0+ 配置的接口,用于代替 web.xml 配置),当 servlet 容器启动 Mvc 利用时会通过 SpringServletContainerInitializer 接口进行加载 从而加载 Mvc 利用信息配置。实现该接口 onStartup 办法,加载利用信息配置。

入口文件代码增加

public class WebInitializer implements WebApplicationInitializer {
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {AnnotationConfigWebApplicationContext ctx=new AnnotationConfigWebApplicationContext();
        // 注册 Mvc 配置信息
        ctx.register(MvcConfig.class);
        // 设置 ServletContext 上下文信息
        ctx.setServletContext(servletContext);
        // 配置转发器 Dispatcher
        ServletRegistration.Dynamic servlet=servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
        servlet.addMapping("/");
        // 启动时即实例化 Bean
        servlet.setLoadOnStartup(1);
    }
}

部署与测试

通过 tomcat 启动我的项目并拜访

此时地址拜访胜利。

​ 当我的项目拜访胜利后,那么问题来了,如果我的项目中存在动态资源文件,Handler 放行解决该如何配置,定义的拦截器怎么利用,此时关注 WebMvcConfigurationSupport 父类办法,重写相干办法即可。

// 动态资源 handler 不进行解决 间接响应到客户端
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {configurer.enable();
}

// 配置拦截器
@Bean
public LoginInterceptor loginInterceptor(){return new LoginInterceptor();
}
// 增加拦截器到 mvc 环境
@Override
public void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor());
}

Spring Boot 概念 & 特点

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/image-20200229103633024.png” alt=”image-20200229103633024″ style=”zoom:80%;” />

框架概念

​ 随着动静语言风行(Ruby,Scala,NodeJs 等),Java 开发变得绝对轻便,配置繁琐,开发效率低下,部署流程简单,以及第三方集成难度也绝对较大,针对该环境,Spring Boot 被开发进去,其应用“习惯大于配置指标”, 借助 Spring Boot 可能让我的项目疾速运行起来,同时借助 Spring Boot 能够疾速创立 web 利用并独立进行部署(jar 包 war 包形式,内嵌 servlet 容器),同时借助 Spring Boot 在开发利用时能够不必或很少去进行相干 xml 环境配置,简化了开发,大大提高我的项目开发效率。

​ Spring Boot 是由 Pivotal 团队提供的全新框架,其设计目标是用来简化新 Spring 利用的初始搭建以及开发过程。该框架应用了特定的形式来进行配置,从而使开发人员不再须要定义样板化的配置。通过这种形式,让 Spring Boot 在蓬勃发展的疾速利用开发畛域 (rapid application development) 成为领导者.

框架特点

​ 创立独立 Spring 应用程序、嵌入式 Tomcat,Jetty 容器、无需部署 WAR 包、简化 Maven 及 Gradle 配置、尽可能自动化配置 Spring、间接植入产品环境下的实用功能,比方度量指标、健康检查及扩大配置、无需代码生成及 XML 配置等,同时 Spring Boot 不仅对 web 应用程序做了简化,还提供一系列的依赖包来把其它一些工作做成开箱即用。

Spring Boot 疾速入门

环境:Idea、Maven、Jdk 1.8+、Spring Boot 2.x

创立 Maven 一般我的项目

增加依赖坐标

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.2.2.RELEASE</version>
</parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

​ Spring Boot 的我的项目必须要将 parent 设置为 Spring Boot 的 parent,该 parent 蕴含了大量默认的配置,简化程序的开发。

导入 Spring Boot 的 web 坐标与相干插件

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

增加源代码

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

创立启动程序

在 HelloController.java 所在包下创立 StarterApplication.java

@SpringBootApplication
public class StarterApplication
{public static void main(String[] args) {SpringApplication.run(Starter.class);
    }
}

启动 Spring Boot 利用并测试

这里运行 main 办法即可 通过浏览器拜访 localhost:8080/hello 成果如下:

Spring Boot 外围配置

自定义 Banner 与 Banner 敞开

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/image-20200216162710816.png” alt=”image-20200216162710816″ style=”zoom:80%;” />

​ 在搭建 Spring Boot 我的项目环境时,程序启动后会在控制台打印醒目的 SpringBoot 图标, 图标形容了 Spring Boot 版本信息,这是 Spring Boot 我的项目与 Spring 我的项目启动区别较大的中央,Spring Boot 通过默认 Banner 在程序启动时显示利用启动图标,当然图标咱们也能够进行自定义。

Banner 图标自定义

​ Spring Boot 我的项目启动时默认加载 src/main/resources 目录下的 banner.txt 图标文件, 如果该目录文件未提供, 则应用 Spring Boot 默认图标打印在 main 目录下新建 resources 资源目录, 并在该目录下新建 banner.txt 文本文件。

关上网址: http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20

在线生成图标对应文本并将文本内容 copy 到 banner.txt 中

启动 Spring Boot 利用打印如下:

Banner 图标敞开

如果启动时不想要看到启动图标,这里也能够通过代码进行敞开操作, 批改 StarterApplication 设置 BannerMode 值为 Banner.Mode.OFF, 启动 Spring Boot 利用敞开图标输入性能即可

@SpringBootApplication
public class StarterApplication  {public static void main(String[] args) {SpringApplication springApplication=new SpringApplication(StarterApplication .class);
        // 设置 banner 图标敞开
        springApplication.setBannerMode(Banner.Mode.OFF);
        springApplication.run();}
}

Spring Boot 配置文件

​ Spring Boot 默认会读取全局配置文件,配置文件名固定为:application.properties 或 application.yml,搁置在 src/main/resources 资源目录下, 应用配置文件来批改 SpringBoot 主动配置的默认值;

在 resources 资源目录下增加 application.properties 文件, 配置信息如下:

## 我的项目启动端口号配置
server.port=8989
## 我的项目拜访上下文门路
server.servlet-path=/mvc

## 数据源配置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/hr?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

或者 application.yml 文件

## 端口号  上下文门路
server:
  port: 8989
  servlet:
    context-path: /mvc

## 数据源配置
spring:
  datasource:
    type: com.mchange.v2.c3p0.ComboPooledDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/hr
    username: root
    password: root

Starter 坐标 & 自动化配置

Starter 坐标配置

​ Spring Boot 引入了全新的 Starter 坐标体系,简化企业我的项目开发大部分场景的 Starter pom, 应用程序引入指定场景的 Start pom 相干配置就能够打消,通过 Spring Boot 就能够失去主动配置的 Bean。

Web starter

应用 Spring MVC 来构建 RESTful Web 利用,并应用 Tomcat 作为默认内嵌容器

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Freemarker Starter & Thymeleaf starter

集成视图技术,引入 Freemarker Starter ,Thymeleaf Starter

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
JavaMail 邮件发送 Starter
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
引入 AOP 环境
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • [] 相干 starter 系列坐标参考
名称 形容
spring-boot-starter 外围 Spring Boot starter,包含主动配置反对,日志和 YAML
spring-boot-starter-actuator 生产筹备的个性,用于帮咱们监控和治理利用
spring-boot-starter-amqp 对”高级音讯队列协定”的反对,通过 spring-rabbit 实现
spring-boot-starter-aop 对面向切面编程的反对,包含 spring-aop 和 AspectJ
spring-boot-starter-batch 对 Spring Batch 的反对,包含 HSQLDB 数据库
spring-boot-starter-cloud-connectors 对 Spring Cloud Connectors 的反对,简化在云平台下(例如,Cloud Foundry 和 Heroku)服务的连贯
spring-boot-starter-data-elasticsearch 对 Elasticsearch 搜寻和剖析引擎的反对,包含 spring-data-elasticsearch
spring-boot-starter-data-gemfire 对 GemFire 分布式数据存储的反对,包含 spring-data-gemfire
spring-boot-starter-data-jpa 对”Java 长久化 API”的反对,包含 spring-data-jpa,spring-orm 和 Hibernate
spring-boot-starter-data-mongodb 对 MongoDB NOSQL 数据库的反对,包含 spring-data-mongodb
spring-boot-starter-data-rest 对通过 REST 裸露 Spring Data 仓库的反对,通过 spring-data-rest-webmvc 实现
spring-boot-starter-data-solr 对 Apache Solr 搜寻平台的反对,包含 spring-data-solr
spring-boot-starter-freemarker 对 FreeMarker 模板引擎的反对
spring-boot-starter-groovy-templates 对 Groovy 模板引擎的反对
spring-boot-starter-hateoas 对基于 HATEOAS 的 RESTful 服务的反对,通过 spring-hateoas 实现
spring-boot-starter-hornetq 对”Java 音讯服务 API”的反对,通过 HornetQ 实现
spring-boot-starter-integration 对一般 spring-integration 模块的反对
spring-boot-starter-jdbc 对 JDBC 数据库的反对
spring-boot-starter-jersey 对 Jersey RESTful Web 服务框架的反对
spring-boot-starter-jta-atomikos 对 JTA 分布式事务的反对,通过 Atomikos 实现
spring-boot-starter-jta-bitronix 对 JTA 分布式事务的反对,通过 Bitronix 实现
spring-boot-starter-mail 对 javax.mail 的反对
spring-boot-starter-mobile 对 spring-mobile 的反对
spring-boot-starter-mustache 对 Mustache 模板引擎的反对
spring-boot-starter-redis 对 REDIS 键值数据存储的反对,包含 spring-redis
spring-boot-starter-security 对 spring-security 的反对
spring-boot-starter-social-facebook 对 spring-social-facebook 的反对
spring-boot-starter-social-linkedin 对 spring-social-linkedin 的反对
spring-boot-starter-social-twitter 对 spring-social-twitter 的反对
spring-boot-starter-test 对罕用测试依赖的反对,包含 JUnit, Hamcrest 和 Mockito,还有 spring-test 模块
spring-boot-starter-thymeleaf 对 Thymeleaf 模板引擎的反对,包含和 Spring 的集成
spring-boot-starter-velocity 对 Velocity 模板引擎的反对
spring-boot-starter-web 对全栈 web 开发的反对,包含 Tomcat 和 spring-webmvc
spring-boot-starter-websocket 对 WebSocket 开发的反对
spring-boot-starter-ws 对 Spring Web 服务的反对

传统的 maven 坐标这里同样实用,如果引入传统 maven 坐标须要思考相干配置类的编写

如果引入相干 starter 坐标这里不存在,能够到这里搜寻。

自动化配置

SpringBoot Starter 坐标版本查看

​ 后面介绍了 SpringBoot Starter 相干坐标,引入 Starter 坐标来简化应用环境的配置。这里以环境搭建 spring-boot-starter-web 坐标来简略剖析 SpringBoot 自动化配置过程。

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

​ 这里引入的 web 环境坐标不像传统的 maven 坐标那样蕴含坐标的版本号,我的项目中引入的 starter 系列坐标对应的版本库对立由父工程坐标对立管制即我的项目中引入的 parent 标签。

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <!--
     父类我的项目对立对我的项目依赖版本对立管制!
  -->  
  <version>2.2.2.RELEASE</version>
</parent>

这里 spring-boot-starter-parent 继承 spring-boot-dependencies 我的项目, 在 spring-boot-dependencies 我的项目中定义了 spring-boot-starter-web 坐标的版本!(spring-boot-dependencies 我的项目中定义了以后 SpringBoot 版本下各个 starter 坐标版本以及依赖的其余坐标版本)

这里依赖的坐标较多, 不在截图展现,可关注 spring-boot-dependencies-2.2.2.RELEASE.pom 文件。

Spring Boot 自动化配置

​ Spring Boot 的我的项目个别都会有 *Application 的入口类,入口类中提供 main 办法,这是一个规范的 Java 应用程序的入口办法。@SpringBootApplication 注解是 Spring Boot 的外围注解,它其实是一个组合注解:

  • @SpringBootApplication

​ 能够看出该注解也是一个组合注解,组合了 @Configuration 注解, 对于 Spring Boot 利用,@SpringBootConfiguration 注解属于 Boot 我的项目的配置注解也是属于一个组合注解,Spring Boot 我的项目中举荐应用 @SpringBootConfiguration 注解, 因为其组合了 @Configuration 注解。

  • @EnableAutoConfiguration

@EnableAutoConfiguration 注解组合了 @AutoConfigurationPackage、@Import(AutoConfigurationImportSelector.class) 注解。

​ @AutoConfigurationPackage 底层也是一个 @Import(AutoConfigurationPackages.Registrar.class),其会把启动类的包下组件都扫描到 Spring 容器中。

​ @Import(AutoConfigurationImportSelector.class) 主动配置的外围类 AutoConfigurationImportSelector.class,该类导入大量的主动配置类,debug 能够发现,其读取的是 classpath 下的 META-INF/spring.factories 下配置文件。

以 WebMvcAutoConfiguration 为例,能够看出该类应用 @Configuration 注解进行标注其为一个配置类。

当然 spring.factories 文件中配置类默认不会都失效,具体哪些配置类失效由配置类上标注的 @ConditionalOnClass 注解来决定,这里理解下 @ConditionalOnClass 注解含意

@ConditionalOnBean         //   当给定的在 bean 存在时, 则实例化以后 Bean
@ConditionalOnMissingBean  //   当给定的在 bean 不存在时, 则实例化以后 Bean
@ConditionalOnClass        //   当给定的类名在类门路上存在,则实例化以后 Bean
@ConditionalOnMissingClass //   当给定的类名在类门路上不存在,则实例化以后 Bean

意味着 WebMvcAutoConfiguration 配置类失效须要环境中存在 Servlet.class,DispatcherServlet.class,WebMvcConfigurer.class 实例,配置类才会失效。

从以上剖析能够得出如下论断:

    `Spring Boot 通过 maven 中的 starter 导入了所需场景下的 jar 包,并通过主启动类上的 @SpringBootApplication 中的 @EnableAutoConfiguration 读取了类门路下的 META-INF/spring.factories 下 EnableAutoConfiguration 的配置类,这些配置类应用 @ConditionalOnClass 来标注,依据 @ConditionalOnClass 标注的约束条件来引入自动化的环境配置。`

Profile 配置

 Profile 是 Spring 用来针对不同环境对不同配置提供反对的全局 Profile 配置应用 application-{profile}.yml,比方 application-dev.yml ,application-test.yml。

通过在 application.yml 中设置 spring.profiles.active=test|dev|prod 来动静切换不同环境, 具体配置如下:

  • application-dev.yml 开发环境配置文件
server:
  port: 8989
  • application-test.yml 测试环境配置文件
server:
  port: 9999
  • application-prod.yml 生产环境配置文件
server:
  port: 8686
  • application.yml 主配置文件
## 环境抉择配置
spring:
  profiles:
    active: dev

启动 Starter 查看控制台输出成果

批改 application.yml 设置 active 值为 prod

## 环境抉择配置
spring:
  profiles:
    active: prod

启动 Starter 再次查看控制台输出成果

日志配置

​ 在开发企业我的项目时,日志的输入对于零碎 bug 定位无疑是一种比拟无效的形式,也是我的项目后续进入生产环境后疾速发现错误解决谬误的一种无效伎俩,所以日志的应用对于我的项目也是比拟重要的一块性能。

​ Spring Boot 默认应用 LogBack 日志零碎,如果不须要更改为其余日志零碎如 Log4j2 等,则无需多余的配置,LogBack 默认将日志打印到管制台上。如果要应用 LogBack,原则上是须要增加 dependency 依赖的

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

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/image-20200229153940293.png” alt=”image-20200229153940293″ style=”zoom:80%;” />

​ 因为新建的 Spring Boot 我的项目个别都会援用 spring-boot-starter 或者 spring-boot-starter-web,而这两个起步依赖中都曾经蕴含了对于spring-boot-starter-logging 的依赖,所以,无需额定增加依赖。

我的项目中日志信息输入

Starter 启动类中增加 Log 日志类, 控制台打印日志信息。

package com.xxxx;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Starter {private static Logger logger = LoggerFactory.getLogger(Starter.class);

    public static void main(String[] args) {logger.info("SpringBoot 利用开始启动...");
        SpringApplication.run(Starter.class);
    }
}

日志输入格局配置

​ 批改 application.yml 文件添日志输入格局信息配置,能够批改 application.yml 文件来管制控制台日志输入格局,同时能够设置日志信息输入到内部文件。

logging:
  pattern:
    console: "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger- %msg%n"
    level: debug
  file:
    path: "."
    name: "springboot.log"

更多日志输入,参考官网

Freemarker & Thymeleaf 视图技术集成

Freemarker 视图集成

​ SpringBoot 外部反对 Freemarker 视图技术的集成,并提供了自动化配置类 FreeMarkerAutoConfiguration,借助自动化配置能够很不便的集成 Freemarker 根底到 SpringBoot 环境中。这里借助入门我的项目引入 Freemarker 环境配置。

  • starter 坐标引入
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
  • 增加 Freemarker 配置信息

    ​ Freemarker 默认默认视图门路文 resources/templates 目录(由自动化配置类 FreemarkerProperties 类决定),该目录能够进行在 application.yml 中进行批改。

批改 application.yml 增加 freemarker 根本配置如下:

spring:
  freemarker:
    suffix: .ftl
    content-type: text/html
    charset: UTF-8
    template-loader-path: classpath:/views/
  • 编写 IndexController 控制器转发视图
package com.xxxx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class IndexController {@RequestMapping("index")
    public String index(){return "index";}
}
  • views 目录下增加 index.ftl 视图

  • 启动 Starter 拜访

Thymeleaf 视图集成

​ SpringBoot 反对多种视图技术集成, 并且 SpringBoot 官网举荐应用 Thymeleaf 作为前端视图页面,这里实现 Thymeleaf 视图集成,借助入门我的项目引入 Thymeleaf 环境配置。

  • starter 坐标引入
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  • 增加 Thymeleaf 配置信息

    ​ Thymeleaf 默认默认视图门路文 resources/templates 目录(由自动化配置类 FreemarkerProperties 类决定),该目录能够进行在 application.yml 中进行批改。

## 环境抉择配置
spring:
  thymeleaf:
    prefix: classpath:/html/
    ## 敞开 thymeleaf 页面缓存
    cache: false
  • 编写 IndexController 控制器转发视图
@Controller
public class IndexController {@RequestMapping("index")
    public String index(Model model){model.addAttribute("msg","hello SpringBoot");
        return "index";
    }
}
  • html 目录下增加 index.html 视图

批改 Thymeleaf 模板默认寄存门路(在 resources 目录下创立 html 文件夹)

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
 <h1 th:text="${msg}"></h1>
</body>
</html>
  • 启动 Starter 拜访

SpringBoot 动态资源拜访

从入门我的项目中能够看到: 对于 Spring Mvc 申请拦挡规定为‘/’,Spring Boot 默认动态资源门路如下:

public class ResourceProperties {private static final String[] CLASSPATH_RESOURCE_LOCATIONS = new String[]{"classpath:/META-INF/resources/", "classpath:/resources/", "classpath:/static/", "classpath:/public/"};
    private String[] staticLocations;
    private boolean addMappings;
    private final ResourceProperties.Chain chain;
    private final ResourceProperties.Cache cache;

即: 咱们能够在 resources 资源目录下寄存 web 利用动态资源文件。

在 resources 目录下创立 static 或者 public 寄存 images、js、css 等动态资源文件

浏览器拜访:

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/1564045973581.png” alt=”1564045973581″ style=”zoom: 40%;” />

SpringBoot 利用打包与部署

​ 当我的项目开发结束进行部署上线时,须要对我的项目进行打包操, 入门中构建的我的项目属于一般利用,因为 SpringBoot 内嵌 Tomcat 容器, 所有打包后的 jar 包默认能够自行运行。

Jar 包部署

配置打包命令

​ idea 下配置 clean compile package -Dmaven.test.skip=true 执行打包命令,target 目录失去待部署的我的项目文件。

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/image-20200229222952894.png” alt=”image-20200229222952894″ style=”zoom:50%;” />

部署并拜访

​ 关上本地 dos 窗口, 执行 java -jar 命令 部署已打好的 jar 包文件

浏览器拜访

<img src=”images\image-20200229223320543.png” alt=”image-20200229223320543″ style=”zoom:50%;” />

war 包部署

​ War 包模式部署 Web 我的项目在生产环境中是比拟常见的部署形式,也是目前大多数 web 利用部署的计划,这里对于 Spring Boot Web 我的项目进行打包部署步骤如下

pom.xml 批改

  • 利用类型批改

因为入门我的项目构建的我的项目默认为 jar 利用,所以这里打 war 须要作如下批改

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/image-20200229224431677.png” alt=”image-20200229224431677″ style=”zoom:80%;” />

  • 内嵌 tomcat 疏忽

构建 SPringBoot 利用时,引入的 spring-boot-starter-web 默认引入 tomcat 容器,这里疏忽掉内容 tomcat

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

  <build>
    <!--
       配置生成的 war 文件名
    -->   
    <finalName>springboot</finalName>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>

Starter 批改

​ 增加容器启动加载文件(相似于读取 web.xml), 这里通过继承 SpringBootServletInitializer 类并重写 configure 办法来实现,在部署我的项目时指定内部 tomcat 读取我的项目入口办法。

@SpringBootApplication
public class Starter  extends SpringBootServletInitializer {private static Logger logger = LoggerFactory.getLogger(Starter.class);

    public static void main(String[] args) {logger.info("SpringBoot 利用开始启动...");
        SpringApplication.run(Starter.class);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {return  builder.sources(Starter.class);
    }
}

部署并拜访

  • 内部 tomcat 部署并拜访

<img src=”https://nuibi.oss-cn-beijing.aliyuncs.com/img/image-20200229225119792.png” alt=”image-20200229225119792″ style=”zoom: 70%;” />

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
正文完
 0