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

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>

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理