SpringBoot整合各种主流组件实战

1、 SpringBoot整合Mybatis

添加Mybatis的起步依赖

<!--mybatis起步依赖-->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.2</version>
</dependency>
<!-- MySQL连接驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

添加数据库连接信息

在application.properties中添加数据量的连接信息

#DB Configuration:
spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root

创建user表

在test数据库中创建user表

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(50) DEFAULT NULL,
  `password` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123');
INSERT INTO `user` VALUES ('2', 'lisi', '123');

创建实体Bean

/**
 * @author 迷迷糊糊
 * @date 2020/6/5
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    private int id;
    private String username;
    private String password;

}

编写Mapper

@Mapper
public interface UserMapper {
	public List<User> queryUserList();
}

注意:@Mapper标记该类是一个mybatis的mapper接口,可以被spring boot自动扫描到spring上下文中

配置Mapper映射文件

在src\main\resources\mapper路径下加入UserMapper.xml配置文件"

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="queryUserList" resultType="user">
        select * from user
    </select>
</mapper>

在application.properties中添加mybatis的信息

#spring集成Mybatis环境
mybatis:
  type-aliases-package: com.example.entity
  mapper-locations: mapper/*Mapper.xml

service层

/**
 * @author 迷迷糊糊
 * @date 2020/6/5
 */
public interface IUserService {

    /**
     * 获取用户信息
     * @return
     */
    List<User> getAllUsers();

}

@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;

    @Override
    public List<User> getAllUsers() {
        return userMapper.queryUserList();
    }
}

编写测试Controller

/**
 * @author 迷迷糊糊
 * @date 2020/6/5
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    @GetMapping
    @ResponseBody
    public List<User> getUsers(){
        return userService.getAllUsers();
    }
}

测试

在这里插入图片描述

2、SpringBoot整合Junit

添加Junit的起步依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

编写测试类

package com.itheima.test;

import com.itheima.MySpringBootApplication;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
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 java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class DemoApplicationTests {

    @Resource
    private UserMapper userMapper;

    @Test
    void testUser() {
        System.out.println(userMapper.queryUserList());
    }

}

控制台打印信息
在这里插入图片描述

3、德鲁伊数据源

/**
 * @author 迷迷糊糊
 * @date 2020/6/5
 */
@Configuration
public class DruidConfig {
    
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }
}
spring:
  datasource:
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
    type: com.alibaba.druid.pool.DruidDataSource
    #   数据源其他配置
    initialSize: 5
    minIdle: 5
    maxActive: 20
    maxWait: 60000
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: SELECT 1 FROM DUAL
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    #   配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500


重新运行
在这里插入图片描述

看后台已经切换了

还有监控呢?

完善配置文件

/**
 * @author 迷迷糊糊
 * @date 2020/6/5
 */
@Configuration
public class DruidConfig {

    /**
     * 注入数据源
     * @return
     */
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druid() {
        return new DruidDataSource();
    }


    /**
     * 配置监控
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        HashMap<String, String> map = new HashMap<>(2);
        map.put("loginUsername","xinzhi");
        map.put("loginPassword","123456");
        bean.setInitParameters(map);
        return bean;
    }

    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>();
        bean.setFilter(new WebStatFilter());
        HashMap<String, String> map = new HashMap<>(8);
        map.put("exclusions","*.js");
        bean.setInitParameters(map);
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }

}

搞定

在这里插入图片描述

4、Thymeleaf模板引擎

Thymeleaf整合SpringBoot

在pom.xml文件引入thymeleaf

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

在application.properties(application.yml)文件中配置thymeleaf

新建编辑控制层代码HelloController,在request添加了name属性,返回到前端hello.html再使用thymeleaf取值显示。

@GetMapping("/login")
public String toLogin(HttpServletRequest request){
    request.setAttribute("user","zhangsan");
    return "login";
}

新建编辑模板文件,在resources文件夹下的templates目录,用于存放HTML等模板文件,在这新增hello.html,添加如下代码。

<!DOCTYPE html> 
<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
<head> 
    <meta charset="UTF-8"/> 
    <title>springboot-thymeleaf demo</title> 
</head> 

<body> 
    <p th:text="'hello, ' + ${name} + '!'" /> 
</body> 
</html>

切记:使用Thymeleaf模板引擎时,必须在html文件上方添加该行代码使用支持Thymeleaf。

<html lang="en" xmlns:th="http://www.thymeleaf.org"> 
  1. 启动项目,访问http://localhost:8080/user/login,看到如下显示证明SpringBoot整合Thymeleaf成功。

在这里插入图片描述

8、路径映射

如果觉得写controller太麻烦一次性多映射一些常用的地址

@Override
protected void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login.html");
registry.addViewController("/register").setViewName("register.html");
super.addViewControllers(registry);
}

5、集成Swagger终极版

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
/**
 * @author 迷迷糊糊
 * @date 2020/6/6
 */
@EnableSwagger2
@Configuration
public class SwaggerConfig {
    @Bean
    public Docket customDocket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                        .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                //文档说明
                .title("迷糊测试专用")
                //文档版本说明
                .version("1.0.0")
                .description("迷糊测试专用2")
                .license("Apache 2.0")
                .build();
    }
}
/**
 * @author 迷迷糊糊
 * @date 2020/6/5
 */
@Controller
@RequestMapping("/user")
@Api("用户接口测试")
public class UserController {

    @Resource
    private IUserService userService;

    @GetMapping("/toLogin")
    public String toLogin(HttpServletRequest request) {
        request.setAttribute("user", "zhangsan");
        return "login";
    }

    @GetMapping
    @ResponseBody
    @ApiImplicitParams(
            {

            }
    )
    public List<User> getUsers() {
        return userService.getAllUsers();
    }

    @GetMapping("/{id}")
    @ResponseBody
    @ApiImplicitParam(name = "id", value = "用户id", dataType = "int")
    @ApiResponse(code = 200,message = "查找成功")
    public User getUserById(@PathVariable int id) {
        return new User(1,"qwe","ewrwe");
    }

    @PostMapping("/login")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", dataType = "string"),
            @ApiImplicitParam(name = "password", value = "密码", dataType = "string")
    })
    @ApiResponses({
            @ApiResponse(code = 200,message = "登录成功"),
            @ApiResponse(code = 500,message = "登录失败"),
    })
    public User login(String username,String password) {
        return new User(12,username,password);
    }
}

6、SpringBoot整合Redis

添加redis的起步依赖

<!-- 配置使用redis启动器 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

配置redis的连接信息

#Redis
spring.redis.host=127.0.0.1
spring.redis.port=6379

注入RedisTemplate测试redis操作

/**
 * @author 迷迷糊糊
 * @date 2020/6/6
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MySpringBootApplication.class)
public class RedisTest {

    @Resource
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Test
    public void test() throws JsonProcessingException {

        BoundHashOperations<String, Object, Object> hash = redisTemplate.boundHashOps("user:1");
        hash.put("username","zhangsan");
        hash.put("age","12");
        hash.put("password","1233");


        BoundValueOperations<String, String> userList = redisTemplate.boundValueOps("user:list");

        //从redis缓存中获得指定的数据
        String usersJson = userList.get();
        //如果redis中没有数据的话
        if(null==usersJson){
            //查询数据库获得数据
            List<User> users = userMapper.queryUserList();
            //转换成json格式字符串
            ObjectMapper om = new ObjectMapper();
            usersJson = om.writeValueAsString(users);
            //将数据存储到redis中,下次在查询直接从redis中获得数据,不用在查询数据库
            redisTemplate.boundValueOps("user:list").set(usersJson);

            System.out.println("===============从数据库获得数据===============");
        }else{
            System.out.println("===============从redis缓存中获得数据===============");
        }

        System.out.println(usersJson);

    }
}

第一次

在这里插入图片描述

第二次

在这里插入图片描述

7、定时任务

@EnableScheduling
public class MySpringBootApplication
/**
 * @author 迷迷糊糊
 * @date 2020/6/7
 */
@Component
public class MySchedule {

    @Scheduled(fixedDelay = 3000)
    public void fixedDelay(){
        System.out.println("fixedDelay:"+new Date());
    }

    @Scheduled(fixedRate = 3000)
    public void fixedRate(){
        System.out.println("fixedRate:"+new Date());
    }


    @Scheduled(initialDelay = 1000,fixedDelay = 2000)
    public void initialDelay(){
        System.out.println("initialDelay:"+new Date());
    }

    @Scheduled(cron = "0 * * * * ?")
    public void cron(){
        System.out.println("cron:"+new Date());
    }

}

结果

fixedRate:Sun Jun 07 11:16:17 CST 2020
fixedDelay:Sun Jun 07 11:16:17 CST 2020
2020-06-07 11:16:17.337  INFO 11928 --- [           main] com.example.MySpringBootApplication      : Started MySpringBootApplication in 6.028 seconds (JVM running for 8.211)
initialDelay:Sun Jun 07 11:16:18 CST 2020
fixedRate:Sun Jun 07 11:16:20 CST 2020
fixedDelay:Sun Jun 07 11:16:20 CST 2020
initialDelay:Sun Jun 07 11:16:20 CST 2020
initialDelay:Sun Jun 07 11:16:22 CST 2020
fixedRate:Sun Jun 07 11:16:23 CST 2020
fixedDelay:Sun Jun 07 11:16:23 CST 2020
initialDelay:Sun Jun 07 11:16:24 CST 2020
fixedRate:Sun Jun 07 11:16:26 CST 2020
fixedDelay:Sun Jun 07 11:16:26 CST 2020
initialDelay:Sun Jun 07 11:16:26 CST 2020
initialDelay:Sun Jun 07 11:16:28 CST 2020
fixedRate:Sun Jun 07 11:16:29 CST 2020
fixedDelay:Sun Jun 07 11:16:29 CST 2020
initialDelay:Sun Jun 07 11:16:30 CST 2020

区别

1、fixedDelay控制方法执行的间隔时间,是以上一次方法执行完开始算起,如上一次方法执行阻塞住了,那么直到上一次执行完,并间隔给定的时间后,执行下一次。

2、fixedRate是按照一定的速率执行,是从上一次方法执行开始的时间算起,如果上一次方法阻塞住了,下一次也是不会执行,但是在阻塞这段时间内累计应该执行的次数,当不再阻塞时,一下子把这些全部执行掉,而后再按照固定速率继续执行。

3、cron表达式可以定制化执行任务,但是执行的方式是与fixedDelay相近的,也是会按照上一次方法结束时间开始算起。

4、initialDelay 。如: @Scheduled(initialDelay = 10000,fixedRate = 15000
这个定时器就是在上一个的基础上加了一个initialDelay = 10000 意思就是在容器启动后,延迟10秒后再执行一次定时器,以后每15秒再执行一次该定时器

quartz自学

8、集成shiro(先学shiro)

9、整合Spring Data JPA(自学)

添加Spring Data JPA的起步依赖

<!-- springBoot JPA的起步依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

添加数据库驱动依赖

<!-- MySQL连接驱动 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>

在application.properties中配置数据库和jpa的相关属性

#DB Configuration:
spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root

#JPA Configuration:
spring.jpa.database=MySQL
spring.jpa.show-sql=true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming_strategy=org.hibernate.cfg.ImprovedNamingStrategy

创建实体配置实体

@Entity
public class User {
    // 主键
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    // 用户名
    private String username;
    // 密码
    private String password;
    // 姓名
    private String name;
 
    //此处省略setter和getter方法... ...
}

编写UserRepository

public interface UserRepository extends JpaRepository<User,Long>{
    public List<User> findAll();
}

编写测试类

@RunWith(SpringRunner.class)
@SpringBootTest(classes=MySpringBootApplication.class)
public class JpaTest {

    @Autowired
    private UserRepository userRepository;

    @Test
    public void test(){
        List<User> users = userRepository.findAll();
        System.out.println(users);
    }

}

控制台打印信息

在这里插入图片描述

注意:如果是jdk9,执行报错如下:

在这里插入图片描述

原因:jdk缺少相应的jar

解决方案:手动导入对应的maven坐标,如下:

<!--jdk9需要导入如下坐标-->
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值