springboot项目,自动化配置spring相关功能,一键启动。现搭建一个简单的具有数据存取功能的项目,使用的是jpa和hibernate。整个项目分为boot-web,boot-service,boot-dao,boot-base四个模块
(1)boot-web部分
这个部分主要是控制层部分,项目的启动文件,项目的配置
1)控制层部分
TestController
package boot.bootweb;
import boot.bootbase.redis.RedisUtil;
import boot.bootdao.entity.Role;
import boot.bootdao.entity.User;
import boot.bootservice.RoleService;
import boot.bootservice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
@Controller
public class TestController {
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private RedisUtil redisUtil;
@ResponseBody // 返回 Json 数据
@GetMapping("addUser")
private User addUser(){
User user = new User();
user.setName("姓名"+(int)(Math.random()*1000));
return userService.addOne(user); // 成功返回 保存的数据
}
@ResponseBody
@GetMapping("addRole")
private Role addRole(){
Role role=new Role();
role.setName("角色名"+(int)(Math.random()*1000));
return roleService.addOne(role);// 成功返回 保存的数据
}
@ResponseBody
@RequestMapping("/insertUser")
public ResponseEntity<String> insertUser(@RequestParam("name") String name,
HttpServletRequest request){
request.getSession().setAttribute("1", name);
User user=new User();
user.setName(name);
return ResponseEntity.ok( userService.insertUser(user).toString());
}
@ResponseBody
@GetMapping("/testRedis")
public ResponseEntity<String> testRedis(){
this.redisUtil.set("test","缓存值"+(int)(Math.random()*1000));
return ResponseEntity.ok(this.redisUtil.get("test"));
}
}
2)启动文件部分
SpringBootWebApplication
package boot;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootWebApplication.class, args);
}
}
3)项目配置
application.yml
spring:
datasource:
# jdbc:mysql://localhost:3306/test 数据库地址
url: jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root # 数据库用户名 修改为自己数据库用户名和密码
password: 123456 # 数据库密码
driver-class-name: com.mysql.jdbc.Driver # 数据库驱动
## Redis 配置
redis:
## Redis数据库索引(默认为0)
database: 0
## Redis服务器地址
host: 127.0.0.1
## Redis服务器连接端口
port: 6379
## Redis服务器连接密码(默认为空)
password:
jedis:
pool:
## 连接池最大连接数(使用负值表示没有限制)
#spring.redis.pool.max-active=8
max-active: 8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.pool.max-wait=-1
max-wait: -1
## 连接池中的最大空闲连接
#spring.redis.pool.max-idle=8
max-idle: 8
## 连接池中的最小空闲连接
#spring.redis.pool.min-idle=0
min-idle: 0
## 连接超时时间(毫秒)
timeout: 1200
mybatis:
mapper-locations: classpath*:mapper/*.xml
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>
<groupId>boot</groupId>
<artifactId>boot-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>boot-web</name>
<description>Spring Boot with Mysql</description>
<parent>
<groupId>boot</groupId>
<artifactId>bootmysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<!--编译编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--输出编码-->
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--java版本-->
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 添加 user-servcie 的依赖 -->
<dependency>
<groupId>boot</groupId>
<artifactId>boot-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(2)boot-service部分
1)接口
RoleService
package boot.bootservice;
import boot.bootdao.entity.Role;
public interface RoleService {
Role addOne(Role role);
}
UserService
package boot.bootservice;
import boot.bootdao.entity.User;
/**
* @Author y10
* @Create 2020/03/06 13:57
* @Desc
*/
public interface UserService {
User addOne(User user);
Integer insertUser(User user);
}
2)实现类
RoleServiceImpl
package boot.bootservice.impl;
import boot.bootdao.entity.Role;
import boot.bootdao.repository.RoleRepository;
import boot.bootservice.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleRepository roleRepository;
@Override
public Role addOne(Role role){
return this.roleRepository.save(role);
}
}
UserServuceImpl
package boot.bootservice.impl;
import boot.bootdao.dao.UserDao;
import boot.bootdao.entity.User;
import boot.bootdao.repository.UserRepository;
import boot.bootservice.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Autowired
private UserDao userDao;
@Override
public User addOne(User user) {
return this.userRepository.save(user);
}
@Override
public Integer insertUser(User user){
return this.userDao.insert(user);
}
}
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>
<groupId>boot</groupId>
<artifactId>boot-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>user-service</name>
<description>Spring Boot with Mysql</description>
<parent>
<groupId>boot</groupId>
<artifactId>bootmysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<!--编译编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--输出编码-->
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--java版本-->
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 添加 user-dao 的依赖 -->
<dependency>
<groupId>boot</groupId>
<artifactId>boot-dao</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(3)boot-dao
1)dao 数据库连接部分
UserDao
package boot.bootdao.dao;
import boot.bootdao.entity.User;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserDao {
Integer insert(User user);
}
2)entity 实体类部分
Role
package boot.bootdao.entity;
import javax.persistence.*;
@Entity(name="role")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Integer id;
@Column(name = "rname") //设置数据库字段名
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
User
package boot.bootdao.entity;
import javax.persistence.*;
@Entity(name = "user") //设置实体名, 在数据库中是表名
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO) //设置自动增长
@Column(name = "id")
private Integer id;
@Column(name = "name") //设置数据库字段名
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
3)repository jpa部分
RoleRepository
package boot.bootdao.repository;
import boot.bootdao.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role,Integer> {
}
UserRespository
package boot.bootdao.repository;
import boot.bootdao.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User, Integer> {
}
4)resources中的mapper部分
UserDao
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="boot.bootdao.dao.UserDao">
<insert id="insert" parameterType="boot.bootdao.entity.User">
insert into
user (
name
)
values (
#{name}
)
</insert>
</mapper>
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>
<groupId>boot</groupId>
<artifactId>boot-dao</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>boot-dao</name>
<description>Spring Boot with Mysql</description>
<parent>
<groupId>boot</groupId>
<artifactId>bootmysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<!--编译编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--输出编码-->
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--java版本-->
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- 添加 user-base 的依赖 -->
<dependency>
<groupId>boot</groupId>
<artifactId>boot-base</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
(4)boot-base 公共通用部分
pojo 公共实体对象
redis 缓存部分
RedisConfig
package boot.bootbase.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.nio.charset.Charset;
/**
* @ClassName: RedisConfig
* @Description: Redis配置
* @author: y10
* @date: 2020年03月07日 下午2:52:24
*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public CacheManager cacheManager(@Qualifier("redisTemplate") RedisTemplate template) {
return new RedisCacheManager(template);
}
@Bean("redisTemplate")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
Object.class);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
RedisTemplate<String, Object> template = new RedisTemplate<>();
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(Charset.forName("UTF-8"));
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
return template;
}
}
RedisUtil
package boot.bootbase.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
*
* @Description: spring boot 的redis工具类
*/
@Component
public class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public String get(final String key) {
Object result = null;
redisTemplate.setValueSerializer(new StringRedisSerializer());
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
if (result == null) {
return null;
}
return result.toString();
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public boolean hmset(String key, Map<String, String> value) {
boolean result = false;
try {
redisTemplate.opsForHash().putAll(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public Map<String, String> hmget(String key) {
Map<String, String> result = null;
try {
result = redisTemplate.opsForHash().entries(key);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
}
util 通用方法类
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="httpzz://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>
<groupId>boot</groupId>
<artifactId>boot-base</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>boot-base</name>
<description>Spring Boot with Mysql</description>
<parent>
<groupId>boot</groupId>
<artifactId>bootmysql</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<!--编译编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--输出编码-->
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--java版本-->
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
主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>
<!-- 父项目 BOOTMYSQL 的版本信息 -->
<groupId>boot</groupId>
<artifactId>bootredis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
<name>BOOTREDIS</name>
<description>Spring Boot with Mysql ,Mybatis and Redis</description>
<!-- 继承说明:这里继承SpringBoot提供的父工程 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.16.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<!-- 声明子模块 -->
<modules>
<module>boot-base</module>
<module>boot-dao</module>
<module>boot-service</module>
<module>boot-web</module>
</modules>
<properties>
<!--编译编码-->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!--输出编码-->
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<!--java版本-->
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.15</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.3</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Camden.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>