SpringMVC配置太多?试试SpringBoot

SpringMVC相信大家已经不再陌生了,大家可能对于Spring的各种XML配置已经产生了厌恶的感觉,Spring官方发布的Springboot 已经很长时间了,Springboot是一款“约定优于配置”的轻量级框架;Springboot首先解决的就是各种繁琐的XML配置,你可以不用任何XML配置,进行web服务的搭建,其次是Springboot本身就继承了web服务器,如果说前端开发人员想在本地启动后端服务不需要进行各种配置,几乎可以做到一键启动。

再有就是目前大热的微服务,而Springboot恰恰满足了快速开发微服务的开发场景;对于目前主流的框架Spring+MyBatis+redis的集成,好吧直接看代码...

以下代码是整个开发框架集成完之后的,关于Spring官方那一套如何编写启动类,如何配置端口这些随便google一大把的我就不再本文说明了。下面的代码,mybatis mapper我就不贴了,平常怎么写现在也一样,还有redis存数据取数据什么的。本文给的都是划的重点啊!

1.数据源以及其他的配置文件(PS:说好了不配置,怎么刚开始就上配置? 答:不配置也可以,如果你想把数据源硬编码写死的话。^_^)

下面给的是YML的配置文件方式,YML被各种主流的开发语言所支持,相当于常见的.properties文件。

1jedis : 2 pool : 3 host : 127.0.0.1 4 port : 6379 5 config : 6 maxTotal: 100 7 maxIdle: 10 8 maxWaitMillis : 100000 9server : 10 port : 8080 11 12jdbc: 13 datasource: 14 name: test 15 url: jdbc:mysql://127.0.0.1:3306/test 16 username: root 17 password: 123456 18 # 使用druid数据源 19 type: com.alibaba.druid.pool.DruidDataSource 20 driver-class-name: com.mysql.jdbc.Driver 21 filters: stat 22 maxActive: 20 23 initialSize: 1 24 maxWait: 60000 25 minIdle: 1 26 timeBetweenEvictionRunsMillis: 60000 27 minEvictableIdleTimeMillis: 300000 28 validationQuery: select 'x' 29 testWhileIdle: true 30 testOnBorrow: false 31 testOnReturn: false 32 poolPreparedStatements: true 33 maxOpenPreparedStatements: 20 34 35# LOGGING 36logging: 37 level: 38 com.ibatis:DEBUG

 2.Springboot启动类

1package com.tony.spring.boot; 2import org.mybatis.spring.annotation.MapperScan; 3import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration; 4import org.springframework.beans.factory.annotation.Value; 5import org.springframework.boot.SpringApplication; 6import org.springframework.boot.autoconfigure.EnableAutoConfiguration; 7import org.springframework.boot.autoconfigure.SpringBootApplication; 8import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer; 9import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer; 10import org.springframework.boot.web.servlet.ServletComponentScan; 11import org.springframework.boot.web.support.SpringBootServletInitializer; 12/** 13 * Created by zhang.tao on 2017/4/19. 14 */ 15@SpringBootApplication(exclude = MybatisAutoConfiguration.class) 16@ServletComponentScan 17@EnableAutoConfiguration 18@MapperScan("com.tony.spring.boot.mapper") 19public class Application extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer { 20 @Value("${server.port}") 21 private int port;//应用的端口 22 /** 23 * 启动入口 24 * @param args 25 */ 26 public static void main(String ... args){ 27 SpringApplication.run(Application.class, args); 28 } 29 /** 30 * 自定义端口 31 */ 32 @Override 33 public void customize(ConfigurableEmbeddedServletContainer container) { 34 container.setPort(port); 35 } 36}

3.配置Mysql数据源 

1import java.sql.SQLException; 2import javax.sql.DataSource; 3import org.slf4j.Logger; 4import org.slf4j.LoggerFactory; 5import org.springframework.boot.bind.RelaxedPropertyResolver; 6import org.springframework.context.EnvironmentAware; 7import org.springframework.context.annotation.Bean; 8import org.springframework.context.annotation.Configuration; 9import org.springframework.core.env.Environment; 10import org.springframework.transaction.annotation.EnableTransactionManagement; 11import com.alibaba.druid.pool.DruidDataSource; 12@Configuration 13@EnableTransactionManagement 14public class DataBaseConfiguration implements EnvironmentAware { 15 private RelaxedPropertyResolver propertyResolver; 16 private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class); 17 private Environment env; 18 @Override 19 public void setEnvironment(Environment env) { 20 this.env = env; 21 this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.datasource."); 22 } 23 /** 24 * 配置数据源 25 * @Description TODO 26 * @return 27 */ 28 @Bean(name = "dataSource",destroyMethod = "close") 29 public DataSource dataSource() { 30 log.debug(env.getActiveProfiles().toString()); 31 32 DruidDataSource dataSource = new DruidDataSource(); 33 dataSource.setUrl(propertyResolver.getProperty("url")); 34 dataSource.setUsername(propertyResolver.getProperty("username"));//用户名 35 dataSource.setPassword(propertyResolver.getProperty("password"));//密码 36 dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name")); 37 dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize"))); 38 dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive"))); 39 dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle"))); 40 dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait"))); 41 dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis"))); 42 dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); 43 dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery")); 44 dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow"))); 45 dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle"))); 46 dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn"))); 47 dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements"))); 48 dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); 49 try { 50 dataSource.init(); 51 } catch (SQLException e) { 52 53 } 54 return dataSource; 55 } 56}

4.Redis数据源配置.

1import org.springframework.beans.factory.annotation.Autowired; 2import org.springframework.beans.factory.annotation.Qualifier; 3import org.springframework.beans.factory.annotation.Value; 4import org.springframework.context.annotation.Bean; 5import org.springframework.context.annotation.Configuration; 6import redis.clients.jedis.JedisPool; 7import redis.clients.jedis.JedisPoolConfig; 8/** 9 * 配置redis数据源 10 * 11 * @ClassName RedisConfig 12 * @author Zhang.Tao 13 * @Date 2017年4月24日 下午5:25:30 14 * @version V2.0.0 15 */ 16@Configuration 17public class RedisConfig { 18 19 20 @Bean(name= "jedis.pool") 21 @Autowired 22 public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config, 23 @Value("${jedis.pool.host}")String host, 24 @Value("${jedis.pool.port}")int port) { 25 return new JedisPool(config, host, port); 26 } 27 28 @Bean(name= "jedis.pool.config") 29 public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal, 30 @Value("${jedis.pool.config.maxIdle}")int maxIdle, 31 @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) { 32 JedisPoolConfig config = new JedisPoolConfig(); 33 config.setMaxTotal(maxTotal); 34 config.setMaxIdle(maxIdle); 35 config.setMaxWaitMillis(maxWaitMillis); 36 return config; 37 } 38}

5.API接口代码(是不是很6,想不想赞一下?)

1import org.springframework.beans.factory.annotation.Autowired; 2import org.springframework.web.bind.annotation.PathVariable; 3import org.springframework.web.bind.annotation.RequestMapping; 4import org.springframework.web.bind.annotation.RestController; 5import com.tony.spring.boot.entity.UserInfo; 6import com.tony.spring.boot.mapper.UserInfoMapper; 7import com.tony.spring.boot.utils.JsonUtil; 8import com.tony.spring.boot.utils.RedisUtil; 9/** 10 * Created by Administrator on 2017/4/19. 11 */ 12@RestController 13@RequestMapping(value="/test") 14public class TestCtrl { 15 16 @Autowired 17 private RedisUtil redisUtil; 18 19 @Autowired 20 private UserInfoMapper userInfoMapper; 21 @RequestMapping(value="/index") 22 public String index(){ 23 return "hello world"; 24 } 25 26 /** 27 * 向redis存储值 28 * @param key 29 * @param value 30 * @return 31 * @throws Exception 32 */ 33 @RequestMapping("/set") 34 public String set(String key, String value) throws Exception{ 35 redisUtil.set(key, value); 36 return "success"; 37 } 38 39 /** 40 * 获取redis中的值 41 * @param key 42 * @return 43 */ 44 @RequestMapping("/get") 45 public String get(String key){ 46 try { 47 return redisUtil.get(key); 48 } catch (Exception e) { 49 e.printStackTrace(); 50 } 51 return ""; 52 } 53 54 /** 55 * 获取数据库中的用户 56 * @Description TODO 57 * @param id 58 * @return 59 */ 60 @RequestMapping("/getUser/{id}") 61 public String get(@PathVariable("id")int id){ 62 try { 63 System.err.println(id); 64 UserInfo user= userInfoMapper.selectByPrimaryKey(id); 65 return JsonUtil.getJsonString(user); 66 } catch (Exception e) { 67 e.printStackTrace(); 68 } 69 return ""; 70 } 71}

6.到这里基本上核心的东西差不多了,去Application.java启动就能用了。赶快试试吧

感谢各位开发者在评论中对错误冗余的配置加以指正,本人亲测后已将错误或者多余的部分代码移除了。

最新代码欢迎star https://github.com/xiaour/SpringBootDemo

点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

SSM_基于传统web项目

1.这是一个单模块的项目!有四个配置文件,mybaits,spring。springmvc,web.xml!2.web.xml配置文件,导入spring和springmvc的配置文件,spring配置文件中,获取sqlsession,以及关联mybatis的mpper(增删改查)文件3.mybatis的配置文件则可以不用写

KVM调整cpu和内存

一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid