转载

作为java开发人员,这份SpringBoot教程,你可真得看看

springboot 搭建基于spring工程的脚手架
作用:可以简化配置和依赖管理
特点:快速搭建、内嵌应用服务器、自动配置、无代码生成、也没有xml配置
复制代码

入门案例

1.引入父依赖、指定springboot版本2.1.5

2.添加启动器类

3.编写启动引导类

4.编写处理器

pom.xml

管理maven依赖的版本
<?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>cn.lxg</groupId>
    <artifactId>springboot_luoxg_day01_01</artifactId>
    <version>1.0-SNAPSHOT</version>

    JDK版本
    <properties>
        <java.version>1.8</java.version>
    </properties>

    SpringBoot依赖
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>
</project>
复制代码

controller控制类

package cn.lxg.controller;

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

//返回的结果是字符串
@RestController
public class HelloController {

    @GetMapping("hello")
    public String helloSpringBoot() {
        return "Hello SpringBoot!";
    }

}
复制代码

Application引导类

package cn.lxg;

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

import javax.swing.*;

@SpringBootApplication //表明当前是一个引导类
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}
复制代码

第一种:配置DataSource数据源

1.创建jdbc.properties配置文件

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.username=root
jdbc.password=lncnetwork
复制代码

2.创建jdbcConfig配置类

package cn.lxg.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;

@Configuration// 注解作用,表名当前是一个配置类
@PropertySource("classpath:jdbc.properties") //加载配置文件
public class JdbcConfig {

    //Value 注入配置文件中的数据
    @Value("${jdbc.driverClassName}")
    private String driverClassName;

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

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

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

    @Bean("dataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(this.driverClass);
        dataSource.setUrl(this.url);
        dataSource.setUsername(this.username);
        dataSource.setPassword(this.password);
        return dataSource;
    }
}
复制代码

3.直接调用数据源

package cn.lxg.controller;

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

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.sql.Connection;

//返回的结果是字符串
@RestController
public class HelloController {

    @Resource(name = "dataSource")
    private DataSource dataSource;

    @GetMapping("hello")
    public String helloSpringBoot() {
        System.out.println(dataSource);
        return "Hello SpringBoot!";
    }

}
复制代码

第二种:配置DataSource数据源

1.创建application.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/account
jdbc.username=root
jdbc.password=lncnetwork
复制代码

2.使用ConfigurationProperties注解 注入数据

package cn.lxg.config;

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

import javax.sql.DataSource;

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

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

}

复制代码

第三种:yml文件配置方式

#普通数据配置
name: zhangsan
#对象的配置
person:
  name: zhangsan
  age: 18
  addr: beijing

#行内对象配置
person1: {name: zhangsan,age: 18,addr: beijing}

#配置数据、集合
city:
  - beijing
  - tianjing
  - chognqing

#行内配置数据、集合
city1: [beijing,tianjing,chongqing]

#配置数据、集合(对象数据)
student:
  - name: tom
    age: 18
    addr: beijing
  - name: lucy
    age: 17
    addr: tianjing

#行内配置数据、集合(对象数据)
student1: [{name: tom,age: 17,adrr: tianjing},{name: tom1,age: 16,adrr: tianjing}]

#map 配置
map:
  key1: value1
  key2: value2
复制代码

yml文件获取方式

1、通过注解@Value 获取值

@Value("${name}")
    private String name;
复制代码

2、注解@ConfigurationProperties配置

配置

person:
  name: zhangsan
  age: 18
  addr: beijing
复制代码

类方法

@Controller
@ConfigurationProperties(prefix = "person")
public class Quick3Controller {

    private String name;
    private String addr;

    @RequestMapping("/quick3")
    @ResponseBody
    public String quick2(){
        return name + "  " + addr;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }
}
复制代码

yml 配置文件示例

application.yml

jdbc:
  driverClassName: com.mysql.jdbc.Driver
  url: jdbc:mysql://localhost:3306/account
  username: root
  password: lncnetwork

spring:
  profiles:
    active: a,b//激活a和b的yml配置文件
复制代码

application-a.yml

luoxg:
  name: luoxg
复制代码

application-b.yml

lncnetwork:
  name: nb
复制代码

HelloController

@RestController
//@PropertySource("classpath:application.yml") //加载配置文件
public class HelloController {

    @Resource(name = "dataSource")
    private DataSource dataSource;

    @Value("${luoxg.name}")
    private String luoxg;

    @Value("${lncnetwork.name}")
    private String lncnetwork;
    
}
复制代码

修改tomcat端口

server:
	port: 80
复制代码

spring boot 静态资源存放路径

private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
			"classpath:/META-INF/resources/", "classpath:/resources/",
			"classpath:/static/", "classpath:/public/" };
复制代码

拦截器

1.创建自己的拦截器类(MyInterceptor)实现 HandlerInterceptor

package cn.lxg.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;

@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("MyInterceptor -- preHandle执行了");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.debug("MyInterceptor -- postHandle执行了");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.debug("MyInterceptor -- afterCompletion执行了");
    }
}

复制代码

2.编写一个配置类实现WebMvcConfigurer

package cn.lxg.config;

import cn.lxg.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;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

//    注册拦截器
    @Bean
    public MyInterceptor myInterceptor() {
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor()).addPathPatterns("/*");
    }
}
复制代码

事务管理

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

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
复制代码

2.数据库连接池hikari配置

spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/account
    username: root
    password: lncnetwork
复制代码

3.编写伪访问数据类

@Transactional :开启事务支持

package cn.lxg.service;

import cn.lxg.domain.Account;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    public void save(Account acc) {
        System.out.println("保存账户信息");
    }

    @Transactional//开启事务支持
    public Account selOne(int id) {
        return new Account();
    }

}
复制代码

SpringBoot整合mybatis

1.添加启动器依赖

<dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
 </dependency>
复制代码

2.配置MyBatis:实体类别名包,日志,映射文件等。

mybatis:
  #实体类别名路径
  type-aliases-package: cn.lxg.pojo
  #映射文件地址
  mapper-locations: classpath:mapper/*.xml
  #配置日志
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

复制代码

3.配置MapperScan

package cn.lxg;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import javax.swing.*;

@SpringBootApplication
//扫描mybatis所有业务Mapper的接口
@MapperScan("cn.lxg.mapper")
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}
复制代码

##SpringBoot整合通用Mapper 通过Mapper:可以实现自都给你拼接sql语句;所有的mapper不需要编写任何的方法就也就是sql语句。可以提高开发效率

1.添加启动器依赖

<!--通用Mapper-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.1.5</version>
        </dependency>
复制代码

2.改造AccountMapper继承Mapper

package cn.lxg.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Account {

    private Integer id;
    private String name;
    private Float money;

}

复制代码

3.修改启动引导类Application中的Mapper扫描注解

package cn.lxg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
//扫描mybatis所有业务Mapper的接口
@MapperScan("cn.lxg.mapper")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
复制代码

4.修改Account实体类,添加JAP注解

package cn.lxg.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "account")
public class Account {
    @Id
    //主键回填
    @KeySql(useGeneratedKeys = true)
    private Integer id;

    @Column(name = "name")
//    支持驼峰
    private String name;

    @Column(name = "money")
    private Float money;

}
复制代码

5.改造AccountService实现业务功能

package cn.lxg.service;

import cn.lxg.domain.Account;
import cn.lxg.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class AccountService {

    @Autowired//自动装配
    private AccountMapper accountMapper;

    public void saveAccount(Account acc) {
        accountMapper.insertSelective(acc);
    }

    @Transactional
    public Account findById(int id) {
        Account account = accountMapper.selectByPrimaryKey(id);
        return account;
    }

}
复制代码

6.测试

package cn.lxg.controller;

//返回的结果是字符串 
@RestController
public class HelloController {

    @Autowired
    private AccountService accountService;

    @RequestMapping("findById/{id}")
    public Account findById(@PathVariable Integer id) {
        return accountService.findById(id);
    }

}

复制代码

SpringBoot整合Junit

在springboot编写测试类,则必须要在类上添加@SpringBootTest

1.加入junit启动器

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
复制代码

2.编写测试类

package cn.lxg.service;

import cn.lxg.domain.Account;
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;

import static org.junit.Assert.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AccountServiceTest {

    @Autowired
    private AccountService accountService;

    @Test
    public void saveAccount() {
        Account account = new Account();
        account.setName("罗帅比");
        account.setMoney(99999F);
        System.out.println(account);
        accountService.saveAccount(account);
        System.out.println(account);
    }

    @Test
    public void findById() {
        Account byId = accountService.findById(20);
        System.out.println(byId);
    }
}
复制代码

SpringBoot整合Redis

1.添加启动启动器依赖; spring-boot-starter-data-redis

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

复制代码

2.配置applciation.yml中修改redis的连接参数;(redis需要启动)

redis:
    host: localhost
    port: 6379

复制代码

3.编写测试类应用RedisTemplate操作redis中的5中数据

package cn.lxg.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 javax.sound.midi.Soundbank;

@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void testRedis1() {
//        字符串
        redisTemplate.boundValueOps("name").set("张三");
        System.out.println(redisTemplate.opsForValue().get("name"));
//        hash 散列
        redisTemplate.boundHashOps("h_key").put("name","luoxg");
//        获得key
        redisTemplate.boundHashOps("h_key").keys();
//        获得value
        redisTemplate.boundHashOps("h_key").values();
        System.out.println(redisTemplate.boundHashOps("h_key").get("name"));;
//        list 列表
        redisTemplate.boundListOps("names").leftPush("l");
        redisTemplate.boundListOps("names").leftPush("x");
        redisTemplate.boundListOps("names").leftPush("g");
//      获得list获得值
        System.out.println(redisTemplate.boundListOps("names").range(0,-1));
//        set 集合
        redisTemplate.boundSetOps("ages").add("1","23","19");
        System.out.println(redisTemplate.boundSetOps("ages").members());
//        sorted set 有序集合
        redisTemplate.boundZSetOps("z_key").add("a",30);
        redisTemplate.boundZSetOps("z_key").add("b",20);
        redisTemplate.boundZSetOps("z_key").add("c",10);

        System.out.println(redisTemplate.boundZSetOps("z_key").range(0,-1));

    }

}

复制代码

SpringBoot 项目部署

1.需要添加打包组件将项目中的资源、配置、依赖包打到一个jar包中;可以使用maven的package

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

复制代码

2.部署:java -jar包名

java -jar springboot_luoxg_day01_01-1.0-SNAPSHOT.jar

复制代码

自动配置原理

1.所有的自动配置类都在spring.factories文件中定义;根绝启动器依赖实例化

2、配置流程

1.查找spring-boot-autoconfigure-***.jar
2.查找当前组件对应在上述jar包中的package
3.查看**Properties配置项类
4.到spring boot的application.yml配置文件中修改配置项

复制代码

最后

感谢你的观看,看完有什么的不懂的可以在评论区问我,觉得文章对你有帮助的话记得给我点个赞,我每天都会分享java相关技术文章或行业资讯,欢迎大家关注和转发文章!

原文  https://juejin.im/post/5f13e6c1f265da22db2c330b
正文到此结束
Loading...