DW-CHEN的Java点滴记录之SpringBoot

SpringBoot

  • 部分代码参考:git@github.com:chendingwu/SpringBootExample.git

添加依赖

  • 依赖springboot父工程
 <!--依赖springboot父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>

添加web启动器

  • 为了让spring boot 帮我们完成各种自动配置,我们必须引入SpringBoot 提供的自动配置依赖,我们称为 启动器 。
<!--添加web启动器-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

注意:这里并没有指定版本信息。

  • 因为spring boot的父工程已经对版本进行了管理。这个时候,我们会发现项目中多出了大量的依赖。那些依赖都是spring boot根据spring-boot-starter-web这个依赖自动引入的,而且所有的版本都已经管理好,不会出现冲突

管理jdk版本

<!--管理jdk版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>

pom.xml

<?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>

    <!--依赖springboot父工程-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
    </parent>
    <groupId>springboot-demo</groupId>
    <artifactId>cn.cdw</artifactId>
    <version>1.0-SNAPSHOT</version>

    <!--添加web启动器-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <!--管理jdk版本-->
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>

创建启动器类

  • 启动引导类中必须要加上一个注解 @SpringBootApplication,SpringBoot工程都有一个启动引导类,这个是工程的入口类
package cn.cdw;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * @author DW-CHEN
 * 启动引导类
 * spring boot 工程都有一个启动引导类,这个是工程的入口类
 * 启动引导类必须要加上一个注解:@SpringBootApplication
 */
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

编写Controller

package cn.cdw.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * controller
 * @author DW-CHEN
 */
@RestController
public class HelloController {

    //也可以使用GetMapping("hello")
    @RequestMapping("/hello")
    public String helloController(){
        return "Hello Spring Boot , TEST SUCCESS....";
    }
}

Java配置应用

常用的注解

  • java的配置主要靠java类和一些注解
注解说明
@Configuration声明一个类作为配置类,代替xml配置文件
@Bean声明在方法上,将方法的返回值加入到Bean容器,代替<bean>标签
@Value属性注入
@PropertySource指定外部属性文件

Profile

  • profile用于配置不同环境,profile激活方式
方式操作
在配置文件中配置spring.profiles.active=dev
在虚拟机参数VM options指定-Dspring.profies.active=dev
命令行参数java -jar xxxx.jar --spring.profiles.active=dev

Condition

  • Condition 条件判断功能,可以通过这个功能实现选择性的创建Bean操作

自定义条件

  • 自定义类实现Condition接口,重写matches方法,在matches方法中进行逻辑判断,返回boolean值
  • 判断条件,在初始化Bean时,使用@Conditional(条件类.class)注解

SpringBoot提供的常用条件注解

注解说明
@ConditionalOnProperty判断配置文件中是否有对应的值才初始化Bean
@ConditionalOnClass判断环境中是否有对应的字节码文件才初始化Bean
@ConditionalOnMissingBean判断环境中没有对应的Bean才初始化Bean

Lombok

  • 在我们编写实体类时,经常需要编写构造函数getter , setter方法,属性多的时候,就非常浪费时间我们可以使用Lombok插件解决

IDEA插入Lombok插件

  • File---->Settings—>Plugins----->搜索lombok---->install---->Restart IDE
添加依赖
 <!--添加lombok依赖-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
在实体类使用Lombok注解
package cn.cdw.pojo;

import lombok.Data;

import java.util.Date;
/*
使用lombok注解@Data,自动提供getter ,settter ,hashCode,equals,toString等方法
 */
@Data
public class User {
    private Long id;

    private String userName;

    private String password;

    private String name;

    private Integer age;

    private Integer sex;

    private Date birthday;

    private String note;

    private Date created;

    private Date updated;
}

lombok注解说明

注解说明
@Data自动提供getter,setter,hashCode,equals,toString方法
@Getter自动提供getter方法
@Setter自动提供Setter方法
@Slf4j自动在Bean中提供log变量,其实用的时slf4j的日志功能。

注意

  • 如果IDEA不安装Lombok插件,使用Lombok的注解虽然编译能通过,但是源码会报错,所以为了让IDEA更好的辨别Lombok注解,则才安装插件

SpringBoot整合数据库连接池

hikari数据库连接池

hikari依赖
  • 上面我们在时候,引入jdbc启动器org.springframework.boot:spring-boot-starter-jdbc:2.1.5RELEASE的时候,Spring Boot就已经自动帮我们引入一个连接池了hikari数据库连接池
hikari数据源参数配置
  • sprng boot默认官方的一个数据库连接池,它的效率比阿里巴巴的Druid高效,所以我们只需要再application配置文件中指定数据库相关的参数即可
spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/springboot_test?characterEncoding=UTF-8
    username: root
    password: root

然后再需要的地方注入数据库连接池即可

//注入dataSource
    @Autowired
    private DataSource dataSource;

注意:如果之前有配置过其他的数据库连接池的话,需要把之前的数据库连接池注释掉

测试:启动访问然后以debug打断点查看参数

Spring Boot整合-通用Mapper

添加通用mapper启动器依赖

  • 通用Mapper的作者也为自己的插件编写了启动器,我们直接引入即可。
 <!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>

注意:一旦引入通用Mapper的启动器,会覆盖mybatis官方启动器功能,因此需要移除对官方mybatis启动器的依赖

JPA(持久化注解)

注解说明
@Table指定数据库查询表对应映射到的实体类
@Id指定实体类的某个属性为数据库表的主键ID
@KeySql主键回填,就比如说我们新增数据的时候,主键id是自增的,我们没有设置值,当我们新增完数据后,它会自动把自增的主键id的值回填到当前我们插入的User对象的属性id中
@Column如果数据库表的字段和我们实体类属性一致(支持驼峰),那默认不需要加上该注解。如果不一致,那么需要加上该注解来指定当前实体类某个属性对应数据库表的字段名称

Spring Boot整合Redis

redis启动器依赖

 <!--redis启动器依赖-->
        <dependency>
            <groupId>org.springframework.boot<</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

在配置文件修改redis连接参数(需启动redis)

#redis参数配置
  redis:
    host: localhost
    port: 6379

使用redis的ResisTemplate操作redis中的5中数据类型(string-字符串,hash-散列,list-列表,set-集合,sorted set-有序集合)

编写测试类
package cn.cdw.redis;

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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Set;


/*
Redis测试类
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisTest {

    //注入对redis操作的RedisTemplate
    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test(){
        //操作redis的的五种类型
        //字符串String   opsForValue()或者boundValueOps() 这两个都表示对字符串的操作,其他4中类型都可以
        //设置值
       // redisTemplate.opsForValue().set("str","cdw");

        //对于字符串的操作还有另一种方法
        redisTemplate.boundValueOps("str").set("cdwcdw");

        //获取值
       String str = (String) redisTemplate.opsForValue().get("str");
        System.out.println("字符串的值: "+str);

        //散列 hash
        //设置
        redisTemplate.opsForHash().put("h_key","age",12);
        redisTemplate.boundHashOps("h_key").put("name","cdw");
        //获取域
        Set set=redisTemplate.boundHashOps("h_key").keys();
        System.out.println("散列的域: "+set);

        //获取值
       List list= redisTemplate.opsForHash().values("h_key");
        System.out.println("散列所有域的值: "+list);

        //列表 list
        redisTemplate.opsForList().leftPush("l_key", "a");
        redisTemplate.opsForList().leftPush("l_key", "b");
        redisTemplate.boundListOps("l_key").leftPush("c");

        //获取key里所有的元素 renge(0,-1)0到负一表示获取全部的意思
        List l_list=redisTemplate.opsForList().range("l_key", 0, -1);
        System.out.println("列表所有的值: " + l_list);

        //集合 set 无序
        redisTemplate.opsForSet().add("s_key", 1, 2, 3, 4);
        redisTemplate.boundSetOps("s1_key").add(4, 3, 2, 1);

        //获取值
        Set set1=redisTemplate.opsForSet().members("s_key");
        System.out.println("集合的值: " + set1);
        Set set2=redisTemplate.boundSetOps("s1_key").members();
        System.out.println("集合的值: " + set2);

        //有序集合 sorted set  它会根据后面的赋值大小从小到大进行排序
        redisTemplate.opsForZSet().add("z_key", "a", 30);
        redisTemplate.opsForZSet().add("z_key", "b", 10);
        redisTemplate.boundZSetOps("z_key").add("c", 20);

        //获取值
        Set set3 = redisTemplate.boundZSetOps("z_key").range(0, -1);
        System.out.println("有序集合的值: " + set3);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值