SpringBoot整合Mybatis框架
我们接着来整合一下SpringSecurity依赖,继续感受SpringBoot带来的光速开发体验,只需要导入SpringSecurity的Starter依赖即可:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
导入依赖后,直接启动会报错,是因为有必要的配置我们没有去编写,我们需要指定数据源的相关信息:
spring.datasource.url=jdbc:mysql://localhost:3306/db10?useUnicode=true&characterEncoding=UTF-8&userSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
这是Mybatis自动扫描输出的语句,导入依赖后,我们不需要再去设置Mybatis的相关Bean了,也不需要添加任何@MapperSacn注解,因为starter已经帮助我们做了,它会自动扫描项目中添加了@Mapper注解的接口,直接将其注册为Bean,不需要进行任何配置。
编写mapper接口
import com.example.entry.UserData;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface MainMapper {
@Select("select * from users where username = #{username} limit 1")
UserData findUserByName(String username);
}
当然,如果你觉得每个接口都去加一个@Mapper比较麻烦的话也可以用回之前的方式,直接@MapperScan使用包扫描。
添加Mapper之后,使用方法和SSM阶段是一样的,我们可以将其与SpringSecurity结合使用:
编写service类
import com.example.entry.UserData;
import com.example.mapper.MainMapper;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
@Service
public class UserAuthService implements UserDetailsService {
@Resource
MainMapper mapper;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
UserData data = mapper.findUserByName(username);
if(data == null) throw new UsernameNotFoundException("用户 "+username+" 登录失败,用户名不存在!");
System.out.println(data.toString());
return User
.withUsername(data.getUsername())
.password(data.getPassword())
.roles(data.getRole())
.build();
}
}
最后配置一下自定义验证即可,注意这样之前配置文件里面配置的用户就失效了:
编写config类
import com.example.service.UserAuthService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.annotation.Resource;
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Resource
UserAuthService service;
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/index").permitAll()
.anyRequest().hasAnyRole("user","admin")
.and()
.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.userDetailsService(service)
.passwordEncoder(new BCryptPasswordEncoder());
}
}
实际上,SpringBoot会自动为Mybatis配置数据源,默认使用的就是HikariCP数据源。
entry实体类
import lombok.Data;
@Data
public class UserData {
int id;
String username;
String password;
String role;
}
此时,controller类显得很多余
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MainController {
// requesMapping测试地址:index,
@RequestMapping("/index")
@ResponseBody
public String index(){
return "你好,欢迎访问";//这里的name是用来测试数据注入是否成功
}
}
数据库
/*
Navicat MySQL Data Transfer
Source Server : fiveGods
Source Server Version : 80016
Source Host : localhost:3306
Source Database : db10
Target Server Type : MYSQL
Target Server Version : 80016
File Encoding : 65001
Date: 2022-03-14 21:02:58
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) DEFAULT NULL,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`role` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES (null, 'test', '$2a$10$9t6WBfMUYkjRDzoISpo6C.VYsJZzGrEk9dyx3QyGUzhDDSqBrNStC', 'admin');
INSERT INTO `users` VALUES (null, 'and', 'and', 'user');