1. springboot整合junit
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
package com.jcli.service;
import org.springframework.stereotype.Service;
@Service
public class UserService {
public String getUser(){
System.out.println("获取用户信息:");
return "zhangsan 这是";
}
}
package com.jcli.test;
import com.jcli.service.UserService;
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;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootApplicationTests {
@Autowired
UserService userService;
@Test
public void getUser(){
String userInfo = userService.getUser();
System.out.println(userInfo);
}
}
@RunWith(SpringRunner.class) 使用springrunner运行器
@SpringBootTest 启用springboot测试使用的方式和之前的spring的使用方式差不多。
2. springboot整合mybatis
1.准备数据库创建表
2.添加起步依赖
3.创建POJO
4.创建mapper接口
5.创建映射文件
6.配置yml 指定映射文件位置
7.创建启动类,加入注解扫描
8.创建service controller 进行测试
InvalidConnectionAttributeException异常:
3. springboot整合redis
1.添加起步依赖
2.准备好redis服务器 并启动
3.在SerService中的方法中使用
3.1 注入redisTemplate
3.2 在方法中进行调用
4.配置yml 配置redis的服务器的地址
redis的序列化机制
出现了乱码,这个是由于redis的默认的序列化机制导致的。并不是错误,由于序列化机制,导致我们数据无法正常显示。如果有代码的方式获取则是可以获取到数据的。
1,默认的情况下redisTemplate操作key vlaue的时候 必须要求 key一定实现序列化 value 也需要实现序列化
2,默认的情况下redisTemplate使用JDK自带的序列化机制:JdkSerializationRedisSerializer
3,JDK自带的序列化机制中要求需要key 和value 都需要实现Serializable接口
4. RedisTemplate支持默认以下几种序列化机制:机制都实现了RedisSerializer接口
+ OxmSerializer
+ GenericJackson2JsonRedisSerializer
+ GenericToStringSerializer
+ StringRedisSerializer
+ JdkSerializationRedisSerializer
+ Jackson2JsonRedisSerializer
自定义序列化机制:定义key 为字符串序列化机制,value:为JDK自带的方式。
@SpringBootApplication
@MapperScan(basePackages = "com.jcli.dao")
//MapperScan 用于扫描指定包下的所有的接口,将接口产生代理对象交给spriing容器
public class MybatisApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisApplication.class,args);
}
@Bean
public RedisTemplate<Object, Object> redisTemplate(
RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
//设置key的值为字符串序列化方式 那么在使用过程中key 一定只能是字符串
template.setKeySerializer(new StringRedisSerializer());
//设置value的序列化机制为JDK自带的方式
template.setValueSerializer(new JdkSerializationRedisSerializer());
return template;
}
}