SpringBoot搭建基于Spring+SpringMvc+Mybatis的REST服务

Maven Plugin管理

通常,让你的Maven POM文件继承 spring-boot-starter-parent,并声明一个或多个 Starter POMs依赖即可。

spring-boot-starter-parent
1 <parent>
2      <groupId>org.springframework.boot</groupId>
3      <artifactId>spring-boot-starter-parent</artifactId>
4      <version>1.5.6.RELEASE</version>
5 </parent>
View Code
其他 Starter POMs依赖
 1 <!-- spring-boot的web启动的jar包 -->
 2         <dependency>
 3             <groupId>org.springframework.boot</groupId>
 4             <artifactId>spring-boot-starter-web</artifactId>
 5         </dependency>
 6         <dependency>
 7             <groupId>org.springframework.boot</groupId>
 8             <artifactId>spring-boot-starter-test</artifactId>
 9         </dependency>
10         <dependency>
11             <groupId>org.springframework.boot</groupId>
12             <artifactId>spring-boot-devtools</artifactId>
13             <optional>true</optional>
14             <scope>true</scope>
15         </dependency>
16         <dependency>
17             <groupId>org.springframework.boot</groupId>
18             <artifactId>spring-boot-starter-data-jpa</artifactId>
19         </dependency>
20         <dependency>
21             <groupId>org.springframework.boot</groupId>
22             <artifactId>spring-boot-starter-data-redis</artifactId>
23         </dependency>
24         <dependency>
25             <groupId>org.springframework.boot</groupId>
26             <artifactId>spring-boot-starter-aop</artifactId>
27         </dependency>
28         <!-- Spring Boot 集成MyBatis -->
29         <dependency>
30             <groupId>org.mybatis.spring.boot</groupId>
31             <artifactId>mybatis-spring-boot-starter</artifactId>
32             <version>1.3.1</version>
33         </dependency>
34         <dependency>
35             <groupId>com.github.pagehelper</groupId>
36             <artifactId>pagehelper-spring-boot-starter</artifactId>
37             <version>1.0.0</version>
38         </dependency>
View Code

application.properties编写

 1 # 驱动配置信息  
 2 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource  
 3 spring.datasource.url = jdbc:mysql://127.0.0.1:3306/goku_db
 4 spring.datasource.username = root
 5 spring.datasource.password = root
 6 spring.datasource.driverClassName = com.mysql.jdbc.Driver
 7 
 8 #连接池的配置信息  
 9 spring.datasource.initialSize=5  
10 spring.datasource.minIdle=5  
11 spring.datasource.maxActive=20  
12 spring.datasource.maxWait=60000  
13 spring.datasource.timeBetweenEvictionRunsMillis=60000  
14 spring.datasource.minEvictableIdleTimeMillis=300000  
15 spring.datasource.validationQuery=SELECT 1
16 spring.datasource.testWhileIdle=true  
17 spring.datasource.testOnBorrow=false  
18 spring.datasource.testOnReturn=false  
19 spring.datasource.poolPreparedStatements=true  
20 spring.datasource.maxPoolPreparedStatementPerConnectionSize=20  
21 spring.datasource.filters=stat,wall,log4j  
22 spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
23 
24 # mybatis
25 mybatis.type-aliases-package=com.goku.webapi.model
26 mybatis.mapper-locations=classpath:mapping/**/*.xml
27 
28 # Mapper
29 mapper.mappers=com.goku.webapi.mapper
30 mapper.not-empty=false
31 mapper.identity=MYSQL
32 
33 #pagehelper
34 pagehelper.helperDialect=mysql
35 pagehelper.reasonable=true
36 pagehelper.supportMethodsArguments=true
37 pagehelper.params=count=countSql
38 
39 # Redis
40 spring.redis.database=0
41 spring.redis.host=127.0.0.1
42 spring.redis.port=6379
43 spring.redis.password=
44 spring.redis.pool.max-active=8
45 spring.redis.pool.max-wait=-1
46 spring.redis.pool.max-idle=8
47 spring.redis.pool.min-idle=0
48 spring.redis.timeout=0
View Code

config配置类编写

数据库配置

  1 ackage com.goku.webapi.config;
  2 
  3 import com.alibaba.druid.pool.DruidDataSource;
  4 import org.apache.ibatis.session.SqlSessionFactory;
  5 import org.mybatis.spring.SqlSessionFactoryBean;
  6 import org.slf4j.Logger;
  7 import org.slf4j.LoggerFactory;
  8 import org.springframework.beans.factory.annotation.Qualifier;
  9 import org.springframework.beans.factory.annotation.Value;
 10 import org.springframework.context.annotation.Bean;
 11 import org.springframework.context.annotation.Configuration;
 12 import org.springframework.context.annotation.Primary;
 13 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 14 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 15 
 16 import java.sql.SQLException;
 17 import javax.sql.DataSource;
 18 
 19 /**
 20  * Created by nbfujx on 2017/10/19.
 21  */
 22 @Configuration
 23 public class DruidDataBaseConfig {
 24 
 25     private Logger logger = LoggerFactory.getLogger(DruidDataBaseConfig.class);
 26 
 27     @Value("${spring.datasource.url}")
 28     private String dbUrl;
 29 
 30     @Value("${spring.datasource.username}")
 31     private String username;
 32 
 33     @Value("${spring.datasource.password}")
 34     private String password;
 35 
 36     @Value("${spring.datasource.driverClassName}")
 37     private String driverClassName;
 38 
 39     @Value("${spring.datasource.initialSize}")
 40     private int initialSize;
 41 
 42     @Value("${spring.datasource.minIdle}")
 43     private int minIdle;
 44 
 45     @Value("${spring.datasource.maxActive}")
 46     private int maxActive;
 47 
 48     @Value("${spring.datasource.maxWait}")
 49     private int maxWait;
 50 
 51     @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
 52     private int timeBetweenEvictionRunsMillis;
 53 
 54     @Value("${spring.datasource.minEvictableIdleTimeMillis}")
 55     private int minEvictableIdleTimeMillis;
 56 
 57     @Value("${spring.datasource.validationQuery}")
 58     private String validationQuery;
 59 
 60     @Value("${spring.datasource.testWhileIdle}")
 61     private boolean testWhileIdle;
 62 
 63     @Value("${spring.datasource.testOnBorrow}")
 64     private boolean testOnBorrow;
 65 
 66     @Value("${spring.datasource.testOnReturn}")
 67     private boolean testOnReturn;
 68 
 69     @Value("${spring.datasource.poolPreparedStatements}")
 70     private boolean poolPreparedStatements;
 71 
 72     @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
 73     private int maxPoolPreparedStatementPerConnectionSize;
 74 
 75     @Value("${spring.datasource.filters}")
 76     private String filters;
 77 
 78     @Value("{spring.datasource.connectionProperties}")
 79     private String connectionProperties;
 80 
 81     @Bean     //声明其为Bean实例
 82     @Primary  //在同样的DataSource中,首先使用被标注的DataSource
 83     public DataSource dataSource(){
 84         DruidDataSource datasource = new DruidDataSource();
 85 
 86         datasource.setUrl(this.dbUrl);
 87         datasource.setUsername(username);
 88         datasource.setPassword(password);
 89         datasource.setDriverClassName(driverClassName);
 90 
 91         //configuration
 92         datasource.setInitialSize(initialSize);
 93         datasource.setMinIdle(minIdle);
 94         datasource.setMaxActive(maxActive);
 95         datasource.setMaxWait(maxWait);
 96         datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
 97         datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
 98         datasource.setValidationQuery(validationQuery);
 99         datasource.setTestWhileIdle(testWhileIdle);
100         datasource.setTestOnBorrow(testOnBorrow);
101         datasource.setTestOnReturn(testOnReturn);
102         datasource.setPoolPreparedStatements(poolPreparedStatements);
103         datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
104         try {
105             datasource.setFilters(filters);
106         } catch (SQLException e) {
107             logger.error("druid configuration initialization filter", e);
108         }
109         datasource.setConnectionProperties(connectionProperties);
110 
111         return datasource;
112     }
113 
114     @Bean
115     @Primary
116     //配置事物管理
117     public DataSourceTransactionManager masterTransactionManager(){
118         return new DataSourceTransactionManager(dataSource());
119     }
120 }
View Code

redis配置

 1 package com.goku.webapi.config;
 2 
 3 import org.springframework.beans.factory.annotation.Value;
 4 import org.springframework.cache.CacheManager;
 5 import org.springframework.cache.annotation.CachingConfigurerSupport;
 6 import org.springframework.cache.annotation.EnableCaching;
 7 import org.springframework.context.annotation.Bean;
 8 import org.springframework.context.annotation.Configuration;
 9 import org.springframework.data.redis.cache.RedisCacheManager;
10 import org.springframework.data.redis.connection.RedisConnectionFactory;
11 import org.springframework.data.redis.core.RedisTemplate;
12 import org.springframework.data.redis.core.StringRedisTemplate;
13 import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
14 
15 import com.fasterxml.jackson.annotation.JsonAutoDetect;
16 import com.fasterxml.jackson.annotation.PropertyAccessor;
17 import com.fasterxml.jackson.databind.ObjectMapper;
18 
19 /**
20  * Created by nbfujx on 2017/10/19.
21  */
22 @Configuration
23 @EnableCaching
24 public class RedisCacheConfig  extends CachingConfigurerSupport {
25 
26     @Value("${spring.redis.host}")
27     private String host;
28     @Value("${spring.redis.port}")
29     private int port;
30     @Value("${spring.redis.timeout}")
31     private int timeout;
32 
33     //缓存管理器
34     @Bean
35     public CacheManager cacheManager(@SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {
36         RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
37         //设置缓存过期时间
38         cacheManager.setDefaultExpiration(10000);
39         return cacheManager;
40     }
41 
42     @Bean
43     public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory){
44         StringRedisTemplate template = new StringRedisTemplate(factory);
45         setSerializer(template);//设置序列化工具
46         template.afterPropertiesSet();
47         return template;
48     }
49 
50     private void setSerializer(StringRedisTemplate template){
51         Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
52         ObjectMapper om = new ObjectMapper();
53         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
54         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
55         jackson2JsonRedisSerializer.setObjectMapper(om);
56         template.setValueSerializer(jackson2JsonRedisSerializer);
57     }
58 
59 }
View Code

SpringApplication启动类编写

 1 package com.goku.webapi;
 2 
 3 import org.mybatis.spring.annotation.MapperScan;
 4 import org.springframework.boot.SpringApplication;
 5 import org.springframework.boot.autoconfigure.SpringBootApplication;
 6 import org.springframework.boot.web.servlet.ServletComponentScan;
 7 import org.springframework.context.annotation.ComponentScan;
 8 
 9 /**
10  * Created by nbfujx on 2017/10/19.
11  */
12 // Spring Boot 应用的标识
13 @SpringBootApplication
14 @ServletComponentScan
15 @MapperScan("com.goku.webapi.mapper")
16 public class WebapiApplication {
17 
18     public static void main(String[] args) {
19         // 程序启动入口
20         // 启动嵌入式的 Tomcat 并初始化 Spring 环境及其各 Spring 组件
21         SpringApplication.run(WebapiApplication.class,args);
22     }
23 }
View Code

 编写其他相关业务类

model,mapper,service,controller

运行启动程序

查看运行效果

 查看druid数据源监控

 

GITHUB

github :https://github.com/nbfujx/learn-java-demo/tree/master/Goku.WebService.Simple.Single

 

posted @ 2017-10-19 20:07  nbfujx  阅读(488)  评论(0编辑  收藏  举报