Spring Boot入门就靠这一篇

约唱跳rap篮球

简介

不了解spring请出门右转

不了解springMVC请出门左转

特点
  • 基于spring,开箱急用,无需xml配置
  • 不是对spring功能地增强,而是提供了一种快速使用spring的方式
  • 内置springMVC,tomcat
  • 起步依赖和自动配置(SpringBoot的核心功能)
和spring的比较
  • 我们知道Spring是一个代替EJB的轻量级框架,但是它的配置确是重量级的。无论是xml还是全注解都会耗损我们的开发时间。另外它的依赖坐标也非常麻烦,随着而来的不兼容问题也影响开发进度。
  • springBoot基于约定优于配置的思想,省去了大量配置,一定程度地缩短了项目周期

快速入门

代码实现
  • pom依赖

    <!--springboot起步依赖-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.1.RELEASE</version>
    </parent>
    <dependencies>
        <!--mvc-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
    
  • 引导类编写

    @SpringBootApplication
    public class MySpringBootApplication {
        public static void main(String[] args) {
            SpringApplication.run(MySpringBootApplication.class);
        }
    }
    
  • Controller编写

    @RestController
    public class QuickStartController {
        @RequestMapping("/quick")
        public String quick(){
            return "springboot 访问成功!";
        } 
    }
    

当我们写完引导类的时候,就可以启动入口函数来运行。因为boot中内置tomcat,且默认端口是8080,所以启动之后我们直接访问127.0.0.1:8080就可以进入

注解解析
  • @SpringBootApplication:标注SpringBoot的启动类,该注解具备多种功能。包括:
    • @Configuration:基于注解的配置类
    • @EnableAutoConfiguration:自动装配
    • @ComponentScan:注解包扫描,默认扫描统一个包下的bean
  • @RestController:是@Controller和@ResponseBody两个注解的结合体
IDEA热部署
  • 添加pom依赖

    <!--热部署配置-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>
    
  • Settings – Build,Execution,Deployment – Complier – Build project automatically

原理分析

起步依赖分析

即我们通过起步依赖摆脱了版本之间的牵扯

打开我们springboot中pom文件的parentspring-boot-starter-parent.pom,再打开该xml的parentspring-boot-dependencies.pom,我们会发现,如果更改我们项目的pom中的boot版本,发现grandparent的版本也会跟着改变,这便是起步依赖。

如果继续分析spring-boot-starter-web依赖的话,会发现它集成了tomcat,mvc,json等

自动配置分析
  • spring-boot-starter-parent.pom文件中我们可以发现:

    <directory>${basedir}/src/main/resources</directory>
    <includes>
        <include>**/application*.yml</include>
        <include>**/application*.yaml</include>
        <include>**/application*.properties</include>
    </includes>
    

    如果我们想通过配置文件来更改默认设置,那么就需要在固定的目录下,且文件名还需要符合要求。其中properties文件的优先级最高。

  • 我们在org.springframework.boot.autoconfigure下的一个类(这个类可以通过@EnableAutoConfiguration找到)中发现这么一句话:

    "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct."
    

    说明配置文件在这个包下的spring.factories文件中,打开后发现是一些全限定类名的键值对,我们打开一两个之后发现,这些就是该类的配置文件的属性

    或者我们可以直接打开该包下的json数据,里面便是一些默认配置。我们可以通过配置文件去修改,如tomcat的端口号

配置文件

配置文件类型
  • application.yml
  • application.yaml
  • application.properties
YML文件

.yml或者.yaml

  • 配置普通数据

    # 注意空格
    name: haohao
    
  • 配置对象数据

    person:
      name: haohao
      age: 31
      addr: beijing
    # 注意:key1前面的空格个数不限定,在yml语法中,相同缩进代表同一个级别
    #或者
    
    person: {name: haohao,age: 31,addr: beijing}
    
  • 配置数组(List、Set)数据

    city:
      - beijing
      - tianjin
      - shanghai
      - chongqing
      
    #或者
    
    city: [beijing,tianjin,shanghai,chongqing]
    
    #集合中的元素是对象形式
    student:
      - name: zhangsan
        age: 18
        score: 100
      - name: lisi
        age: 28
        score: 88
      - name: wangwu
        age: 38
        score: 90
    # 注意:value1与之间的 - 之间存在一个空格
    
获得配置数据
  • @Value

    	@Value("${person.name}")
        private String name;
    
        @ResponseBody
        @RequestMapping("/wo")
        public String per(){
            return name;
        }
    
  • @ConfigurationProperties

    用于需要配置的属性较多情况,需要加getter和setter方法

    @Controller
    @ConfigurationProperties(prefix = "person")
    public class QuickStartController {
    
        private String name;
        private Integer age;
        
        @RequestMapping("/quick")
        @ResponseBody
        public String quick(){
            return "springboot 访问成功! name="+name+",age="+age;
        }
        
        public void setName(String name) {
            this.name = name;
        }
        
        public void setAge(Integer age) {
            this.age = age;
        }
    }
    

    对于这个注解,需要加上一个pom依赖

    <dependency>
    	<groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <option>true</option>
    </dependency>
    

    看到了getter和setter方法,或许你已经想到了什么,没错,我们可以把这些封装称为一个javabean的实体类。需要在实体类上注入@Component和@ConfigurationProperties,然后在Controller层注入后调用其get方法就完事了

常见配置

可参阅官方文档

# QUARTZ SCHEDULER (QuartzProperties)
spring.quartz.jdbc.initialize-schema=embedded # Database schema initialization mode.
spring.quartz.jdbc.schema=classpath:org/quartz/impl/jdbcjobstore/tables_@@platform@@.sql # Path to the SQL file to use to initialize the database schema.
spring.quartz.job-store-type=memory # Quartz job store type.
spring.quartz.properties.*= # Additional Quartz Scheduler properties.

# ----------------------------------------
# WEB PROPERTIES
# ----------------------------------------

# EMBEDDED SERVER CONFIGURATION (ServerProperties)
server.port=8080 # Server HTTP port.
server.servlet.context-path= # Context path of the application.
server.servlet.path=/ # Path of the main dispatcher servlet.

# HTTP encoding (HttpEncodingProperties)
spring.http.encoding.charset=UTF-8 # Charset of HTTP requests and responses. Added to the "Content-Type" header if not set explicitly.

# JACKSON (JacksonProperties)
spring.jackson.date-format= # Date format string or a fully-qualified date format class name. For instance, `yyyy-MM-dd HH:mm:ss`.

# SPRING MVC (WebMvcProperties)
spring.mvc.servlet.load-on-startup=-1 # Load on startup priority of the dispatcher servlet.
spring.mvc.static-path-pattern=/** # Path pattern used for static resources.
spring.mvc.view.prefix= # Spring MVC view prefix.
spring.mvc.view.suffix= # Spring MVC view suffix.

# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)
spring.datasource.driver-class-name= # Fully qualified name of the JDBC driver. Auto-detected based on the URL by default.
spring.datasource.password= # Login password of the database.
spring.datasource.url= # JDBC URL of the database.
spring.datasource.username= # Login username of the database.

# JEST (Elasticsearch HTTP client) (JestProperties)
spring.elasticsearch.jest.password= # Login password.
spring.elasticsearch.jest.proxy.host= # Proxy host the HTTP client should use.
spring.elasticsearch.jest.proxy.port= # Proxy port the HTTP client should use.
spring.elasticsearch.jest.read-timeout=3s # Read timeout.
spring.elasticsearch.jest.username= # Login username.

整合

整合Mybatis
  • 导入pom依赖

          <!-- mybatis -->
            <dependency>
                <groupId>org.mybatis.spring.boot</groupId>
                <artifactId>mybatis-spring-boot-starter</artifactId>
                <version>1.1.1</version>
            </dependency>
            <!-- mysql -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>8.0.16</version>
            </dependency>
    
  • 编写DAO层

    @Mapper
    public interface CityDao {
    
        /**
         * 查询全部
         * @return world
         */
        @Select("select ID,Name,Population from city")
        List<City> findAll();
    }
    
  • 配置文件

    #DB Configuration:
    spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/world?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect=true
    spring.datasource.username=root
    spring.datasource.password=root
    
    #spring集成Mybatis环境
    #pojo别名扫描包
    mybatis.type-aliases-package=zi10ng.domain
    
  • 编写控制层

    /**
     * @author Zi10ng
     * @date 2019年7月23日13:13:37
     */
    @Controller
    @RequestMapping("/hello")
    public class HelloController {
    
        @Autowired
        private CityDao cityDao;
    
        @ResponseBody
        @RequestMapping("/findAll")
        public String findAll(){
            return cityDao.findAll().get(0).getName();
        }
    
    }
    
  • 可能有人会问,这个怎么没有想SSM中一样扫描一下dao层的包,原因是不用扫描,之前我们说过,在启动类中加的@SpringBootApplication注解,已经扫描过了。当然,如果你不放心,在启动类上加个@MapperScan("package.domain")

整合Junit
  • 导入pom

            <!--测试的起步依赖-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
  • 编写测试类

    /**
     * @author Zi10ng
     * @date 2019年7月23日18:10:02
     */
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = MySpringBootApplication.class)
    public class MapperTest {
        @Autowired
        private CityDao cityDao;
    
        @Test
        public void test() {
            List<City> users = cityDao.findAll();
            System.out.println(users.get(1).getPopulation());
        }
    }
    
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值