Ego的SpringBoot笔记

概述

  1. 什么是spring boot

    便捷搭建spring工程的脚手架,减少xml配置

  2. 为什么要学习spring boot

    1. 解决复杂的配置
    2. 解决混乱的依赖管理

入门

需求:在浏览器中访问http://localhost:8080/hello 输出一串字符

步骤:

  1. 创建工程

  2. 添加依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.5.RELEASE</version>
        </parent>
        <groupId>com.ego</groupId>
        <artifactId>springboot</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
        </dependencies>
    
    </project>
    
  3. 创建启动类

    package com.ego;
    
    /**
     * @author 袁梦达 2019012364
     */
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * spring boot工程都有一个启动引导类,这是工程的入口类
     * 在引导类上加 @SpringBootApplication
     */
    @SpringBootApplication
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
    
  4. 创建处理器controller

    package com.ego.controller;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author 袁梦达 2019012364
     */
    @RestController
    public class HelloController {
    
        @GetMapping("hello")
        public String hello(){
            return "hello,spring boot!";
        }
    }
    
    
  5. 测试

Java配置应用

##尝试Java配置

比较常用的注解:

  • @Configuration:声明一个类作为配置类,代替xml文件
  • @Bean:声明在方法上,将方法的返回值加入Bean容器,代替标签
  • @Value:属性注入
  • @PropertySource:指定外部属性文件

需求:使用Java代码配置数据库连接池,并可以在处理器中注入并使用

步骤:

  1. 添加依赖

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.5.RELEASE</version>
        </parent>
        <groupId>com.ego</groupId>
        <artifactId>springboot</artifactId>
        <version>1.0-SNAPSHOT</version>
    
        <properties>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid</artifactId>
                <version>1.1.6</version>
            </dependency>
        </dependencies>
    
    </project>
    
  2. 创建数据库

  3. 创建数据库连接参数的配置文件jdbc.properties

    jdbc.driverClassName=com.mysql.jdbc.Driver
    jdbc.url=jdbc:mysql://127.0.0.1:3306/test
    jdbc.username=root
    jdbc.password=root
    
  4. 创建配置类

    package com.ego.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    import javax.sql.DataSource;
    
    /**
     * @author 袁梦达 2019012364
     */
    
    @Configuration
    @PropertySource("classpath:jdbc.properties")
    public class JdbcConfig {
    
        @Value("${jdbc.driverClassName}")
        String driverClassName;
    
        @Value("${jdbc.url}")
        String url;
    
        @Value("${jdbc.username}")
        String username;
    
        @Value("${jdbc.password}")
        String password;
    
        @Bean
        public DataSource dataSource(){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(driverClassName);
            dataSource.setUrl(url);
            dataSource.setUsername(username);
            dataSource.setPassword(password);
            return dataSource;
        }
    
    }
    
    
  5. 改造处理器类注入数据源并使用

    package com.ego.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.sql.DataSource;
    
    /**
     * @author 袁梦达 2019012364
     */
    @RestController
    public class HelloController {
    
        @Autowired
        private DataSource dataSource;
    
        @GetMapping("hello")
        public String hello(){
            System.out.println(dataSource);
            return "hello,spring boot!";
        }
    }
    
    

spring boot属性注入方式

需求:将配置文件中的配置项读取到一个对象中

实现:可以使用spring boot提供的注解@ConfigurationProperties,该注解可以将spring boot的配置文件(默认必须为application.properties或application.yml)中的配置项读取到一个对象中

步骤:

  1. 创建配置项类,在该类名上添加@ConfigurationProperties

    package com.ego.config;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    
    /**
     * @author 袁梦达 2019012364
     */
    
    /**
     * @ConfigurationProperties从配置文件中读取配置项
     * prefix表示配置项的前缀(jdbc.XXX)
     * 配置类项中的类变量名必须与配置文件中前缀后的名称松散绑定
     */
    @ConfigurationProperties(prefix = "jdbc")
    public class JdbcProperties {
    
        private String driverClassName;
        private String url;
        private String username;
        private String password;
    
        public String getDriverClassName() {
            return driverClassName;
        }
    
        public void setDriverClassName(String driverClassName) {
            this.driverClassName = driverClassName;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    }
    
    
  2. 将jdbc.properties修改名称为application.properties

  3. 将配置项类注入到配置类

    package com.ego.config;
    
    import com.alibaba.druid.pool.DruidDataSource;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    
    import javax.sql.DataSource;
    
    /**
     * @author 袁梦达 2019012364
     */
    
    @Configuration
    //@PropertySource("classpath:application.properties")
    @EnableConfigurationProperties(JdbcProperties.class)
    public class JdbcConfig {
    
        /*@Value("${jdbc.driverClassName}")
        String driverClassName;
    
        @Value("${jdbc.url}")
        String url;
    
        @Value("${jdbc.username}")
        String username;
    
        @Value("${jdbc.password}")
        String password;
        */
    
        @Bean
        public DataSource dataSource(JdbcProperties jdbcProperties){
            DruidDataSource dataSource = new DruidDataSource();
            dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
            dataSource.setUrl(jdbcProperties.getUrl());
            dataSource.setUsername(jdbcProperties.getUsername());
            dataSource.setPassword(jdbcProperties.getPassword());
            return dataSource;
        }
    
    }
    
    

更优雅简洁的写法:直接将@ConfigurationProperties在方法上使用

package com.ego.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;

/**
 * @author 袁梦达 2019012364
 */

@Configuration
//@PropertySource("classpath:application.properties")
//@EnableConfigurationProperties(JdbcProperties.class)
public class JdbcConfig {

    /*@Value("${jdbc.driverClassName}")
    String driverClassName;

    @Value("${jdbc.url}")
    String url;

    @Value("${jdbc.username}")
    String username;

    @Value("${jdbc.password}")
    String password;
    */

    /*@Bean
    public DataSource dataSource(JdbcProperties jdbcProperties){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(jdbcProperties.getDriverClassName());
        dataSource.setUrl(jdbcProperties.getUrl());
        dataSource.setUsername(jdbcProperties.getUsername());
        dataSource.setPassword(jdbcProperties.getPassword());
        return dataSource;
    }*/

    @Bean
    @ConfigurationProperties(prefix = "jdbc")
    public DataSource dataSource(){
        return new DruidDataSource();
    }

}

多个yml文件配置

yaml是一种简洁的非标记语言。以数据为中心,使用空白,缩进,分行组织数据

  1. 要求:

    1. 配置项之间如果有关系的话需要分行空两格
    2. 配置项如果有值的话,那么需要在冒号之后空一格再写值

    基本格式:

    jdbc:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test
      username: root
      password: root
    
  2. 多个yml配置文件:在spring boot中是允许的。这些配置文件的名称必须为application-***.yml,并且这些配置文件必须要在application.yml中激活后才可以使用

    jdbc:
      driverClassName: com.mysql.jdbc.Driver
      url: jdbc:mysql://127.0.0.1:3306/test
      username: root
      password: root
    
    #激活
    spring:
      profiles:
        active: a,b
    
    
  3. 如果properties和yml配置文件同时存在,两种都有效,如果存在同名的配置项,会以properties文件为主

spring boot整合ssm

lombok应用

lombok是一个插件工具类包,提供了一些注解简化实体类的构造方法,getter,setter等方法的编写

步骤:

  1. 安装lombok插件

  2. 添加lombok对应的依赖到pom.xml

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
    </dependency>
    
  3. 使用注解改造实体类

    package com.ego.pojo;
    
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    
    /**
     * @author 袁梦达 2019012364
     */
    
    @Data
    @Slf4j
    public class Student {
    
        private Integer id;
        private String name;
        private Integer age;
        
    }
    
    

注解:

  • @Data:自动提供getter和setter、hashCode、equals、toString等方法
  • @Getter:自动提供getter方法
  • @Setter:自动提供setter方法
  • @Slf4j:自动在bean中提供log变量,可以使用Slf4j的日志功能

整合spring mvc端口和静态资源

  • 修改tomcat端口

    查询**Properties,设置配置项到application配置文件中

    server:
      port: 80
    
  • 访问项目中的静态资源

    静态资源放置的位置,放置静态资源并访问

    springboot访问静态资源的几种方式
    (1)在src/main/resources/目录下创建
    static文件夹
    (2)在src/main/resources/目录下创建
    resources文件夹
    (3)在src/main/resources/目录下创建
    public文件夹
    (4)在src/main/resources/目录下创建
    META-INF/resources文件夹

整合spring mvc拦截器

步骤:

  1. 编写拦截器(实现HandlerInterceptor)

    package com.ego.Interceptor;
    
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * @author 袁梦达 2019012364
     */
    @Slf4j
    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            log.debug("这是preHandle方法");
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            log.debug("这是postHandle方法");
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            log.debug("这是afterCompletion方法");
        }
    }
    
    
  2. 编写配置类实现WebMvcConfigurer,在该类中添加各种组件

    package com.ego.config;
    
    import com.ego.Interceptor.MyInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    /**
     * @author 袁梦达 2019012364
     */
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
        //注册拦截器
        @Bean
        public MyInterceptor myInterceptor(){
            return new MyInterceptor();
        }
        
        //添加拦截器到spring mvc拦截器链
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
        }
    }
    
    

整合事务和连接池

  • 事务配置

    1. 添加事务相关的启动器依赖,MySQL相关依赖

      <dependency>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-jdbc</artifactId>
      </dependency>
      <dependency>
          <groupId>mysql</groupId>
          <artifactId>mysql-connector-java</artifactId>
          <version>5.1.46</version>
      </dependency>
      
    2. 编写业务类UserService使用事务注解@Transactional

  • 数据库连接池hikari配置

    只需要在application配置文件中指定数据库相关参数

    spring:
      datasource:
        driver-class-name: com.mysql.jdbc.Driver
        url: jdbc:mysql://127.0.0.1:3306/test
        username: root
        password: root
    
    
    

整合mybatis

步骤:

  1. 添加启动器依赖

    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.0.1</version>
    </dependency>
    
  2. 配置mybatis:实体类别名包,日志,映射文件等

    mybatis:
      #实体类别名包路径
      type-aliases-package: com.ego.pojo
      #映射文件路径
      mapper-locations: classpath:mapper/*.xml
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    
  3. 配置MapperScan

    @SpringBootApplication
    @MapperScan("com.ego.mapper") //扫描mybatis所有业务的mapper接口
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    

整合通用Mapper

通用Mapper:可以实现自动拼接sql语句,所有的mapper都不需要编写任何方法,也就是不用编写sqly语句。可以提高开发效率

步骤:

  1. 添加启动器依赖

    <dependency>
        <groupId>tk.mybatis</groupId>
        <artifactId>mapper-spring-boot-starter</artifactId>
        <version>2.1.5</version>
    </dependency>
    
  2. 改造UserMapper继承Mapper

    package com.ego.mapper;
    
    import com.ego.pojo.Student;
    import tk.mybatis.mapper.common.Mapper;
    
    /**
     * @author 袁梦达 2019012364
     */
    public interface UserMapper extends Mapper<Student> {
    }
    
    
  3. 修改启动引导类中的Mapper扫描注解

    @SpringBootApplication
    //@MapperScan("com.ego.mapper") //扫描mybatis所有业务的mapper接口
    @MapperScan("com.ego.mapper")
    public class Application {
        public static void main(String[] args) {
            SpringApplication.run(Application.class, args);
        }
    }
    
  4. 修改User实体类添加jpa注解

    package com.ego.pojo;
    
    import lombok.Data;
    import lombok.extern.slf4j.Slf4j;
    import tk.mybatis.mapper.annotation.KeySql;
    
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    /**
     * @author 袁梦达 2019012364
     */
    
    @Data
    @Table(name = "student")
    public class Student {
    
        @Id
        @KeySql(useGeneratedKeys = true) //主键回填
        private Integer id;
        private String name;
        private Integer age;
    
    }
    
    
  5. 改造UserService实现业务功能

    package com.ego.service;
    
    import com.ego.mapper.UserMapper;
    import com.ego.pojo.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    /**
     * @author 袁梦达 2019012364
     */
    @Service
    public class UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        public Student queryById(Long id){
            return userMapper.selectByPrimaryKey(id);
        }
    
        @Transactional
        public void saveUser(Student student){
            userMapper.insertSelective(student);
        }
    }
    
    

整合测试

package com.ego.controller;

import com.ego.pojo.Student;
import com.ego.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;

/**
 * @author 袁梦达 2019012364
 */
@RestController
public class HelloController {

    @Autowired
    private DataSource dataSource;

    @Value("${ego.name}")
    private String egoName;
    @Value("${daqiao.name}")
    private String daqiaoName;

    @Autowired
    private UserService userService;

    @GetMapping("/user/{id}") //浏览器输入http://localhost:8080/user/1 访问id为1的数据
    public Student queryById(@PathVariable Long id){
        return userService.queryById(id);
    }

    @GetMapping("hello")
    public String hello(){

        System.out.println(egoName);
        System.out.println(daqiaoName);
        System.out.println(dataSource);
        return "hello,spring boot!";
    }
}

整合Junit

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
package com.ego.service;

import com.ego.pojo.Student;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * @author 袁梦达 2019012364
 */

@RunWith(SpringRunner.class)
@SpringBootTest
public class UserServiceTest extends TestCase {

    @Autowired
    private UserService userService;

    @Test
    public void testQueryById() {
        userService.queryById(1L);
    }

    @Test
    public void testSaveUser() {
        Student student = new Student();
        student.setId(7);
        student.setName("test");
        student.setAge(100);
        userService.saveUser(student);
    }
}

spring boot项目部署

将spring boot项目使用maven指令达成jar包并运行测试

步骤:

  1. 需要添加打包组件将项目中的资源、配置、依赖包打到一个jar包中,可以使用maven的package
  2. 部署:java -jar 包名
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值