SpringMVC配置太多?試試SpringBoot

SpringMVC相信你們已經再也不陌生了,你們可能對於Spring的各類XML配置已經產生了厭惡的感受,Spring官方發佈的Springboot 已經很長時間了,Springboot是一款「約定優於配置」的輕量級框架;Springboot首先解決的就是各類繁瑣的XML配置,你能夠不用任何XML配置,進行web服務的搭建,其次是Springboot自己就繼承了web服務器,若是說前端開發人員想在本地啓動後端服務不須要進行各類配置,幾乎能夠作到一鍵啓動。前端

再有就是目前大熱的微服務,而Springboot偏偏知足了快速開發微服務的開發場景;對於目前主流的框架Spring+MyBatis+redis的集成,好吧直接看代碼...java

如下代碼是整個開發框架集成完以後的,關於Spring官方那一套如何編寫啓動類,如何配置端口這些隨便google一大把的我就再也不本文說明了。下面的代碼,mybatis mapper我就不貼了,日常怎麼寫如今也同樣,還有redis存數據取數據什麼的。本文給的都是劃的重點啊!mysql

1.數據源以及其餘的配置文件(PS:說好了不配置,怎麼剛開始就上配置? 答:不配置也能夠,若是你想把數據源硬編碼寫死的話。^_^)git

下面給的是YML的配置文件方式,YML被各類主流的開發語言所支持,至關於常見的.properties文件。github

jedis : 
  pool : 
    host : 127.0.0.1 
    port : 6379 
    config : 
      maxTotal: 100 
      maxIdle: 10 
      maxWaitMillis : 100000
server : 
  port :  8080
   
jdbc:
    datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/test
        username: root
        password: 123456
        # 使用druid數據源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
# MyBatis
mybatis:
    typeAliasesPackage: com.xiaour.spring.boot.entity
    mapperLocations: classpath*:/com/xiaour/spring/boot/mapper/*.xml
    configLocation: classpath:mybatis-config.xml
     
# LOGGING
logging:
    level:
       com.ibatis:DEBUG

2.Springboot啓動web

package com.tony.spring.boot;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
/**
 * Created by zhang.tao on 2017/4/19.
 */
@SpringBootApplication(exclude = MybatisAutoConfiguration.class)
@ServletComponentScan
@EnableAutoConfiguration
@MapperScan("com.tony.spring.boot.mapper")
public class Application  extends SpringBootServletInitializer implements EmbeddedServletContainerCustomizer {
    @Value("${server.port}")
    private int port;//應用的端口
    /**
     * 啓動入口
     * @param args
     */
    public static void main(String ... args){
        SpringApplication.run(Application.class, args);
    }
    /**
     * 自定義端口
     */
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(port);       
    }
}

3.配置Mysql數據源redis

import java.sql.SQLException;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@EnableTransactionManagement
public class DataBaseConfiguration implements EnvironmentAware {
    private RelaxedPropertyResolver propertyResolver;
    private static Logger log = LoggerFactory.getLogger(DataBaseConfiguration.class);
    private Environment env;
    @Override
    public void setEnvironment(Environment env) {
        this.env = env;
        this.propertyResolver = new RelaxedPropertyResolver(env, "jdbc.datasource.");
    }
    /**
     * 配置數據源
     * @Description TODO
     * @return
     */
    @Bean(name = "dataSource",destroyMethod = "close")
    public DataSource dataSource() {
        log.debug(env.getActiveProfiles().toString()); 
          
         DruidDataSource dataSource = new DruidDataSource(); 
         dataSource.setUrl(propertyResolver.getProperty("url")); 
         dataSource.setUsername(propertyResolver.getProperty("username"));//用戶名 
         dataSource.setPassword(propertyResolver.getProperty("password"));//密碼 
         dataSource.setDriverClassName(propertyResolver.getProperty("driver-class-name"));
         dataSource.setInitialSize(Integer.parseInt(propertyResolver.getProperty("initialSize"))); 
         dataSource.setMaxActive(Integer.parseInt(propertyResolver.getProperty("maxActive"))); 
         dataSource.setMinIdle(Integer.parseInt(propertyResolver.getProperty("minIdle"))); 
         dataSource.setMaxWait(Integer.parseInt(propertyResolver.getProperty("maxWait"))); 
         dataSource.setTimeBetweenEvictionRunsMillis(Integer.parseInt(propertyResolver.getProperty("timeBetweenEvictionRunsMillis"))); 
         dataSource.setMinEvictableIdleTimeMillis(Integer.parseInt(propertyResolver.getProperty("minEvictableIdleTimeMillis"))); 
         dataSource.setValidationQuery(propertyResolver.getProperty("validationQuery")); 
         dataSource.setTestOnBorrow(Boolean.getBoolean(propertyResolver.getProperty("testOnBorrow"))); 
         dataSource.setTestWhileIdle(Boolean.getBoolean(propertyResolver.getProperty("testWhileIdle"))); 
         dataSource.setTestOnReturn(Boolean.getBoolean(propertyResolver.getProperty("testOnReturn"))); 
         dataSource.setPoolPreparedStatements(Boolean.getBoolean(propertyResolver.getProperty("poolPreparedStatements"))); 
         dataSource.setMaxPoolPreparedStatementPerConnectionSize(Integer.parseInt(propertyResolver.getProperty("maxOpenPreparedStatements"))); 
         try {
            dataSource.init();
        } catch (SQLException e) {
             
        }
         return dataSource;
    }
}

4.Redis數據源配置.spring

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
/**
 * 配置redis數據源
 *
 * @ClassName RedisConfig
 * @author Zhang.Tao
 * @Date 2017年4月24日 下午5:25:30
 * @version V2.0.0
 */
@Configuration
public class RedisConfig {
      
     
  @Bean(name= "jedis.pool") 
  @Autowired 
  public JedisPool jedisPool(@Qualifier("jedis.pool.config") JedisPoolConfig config,  
              @Value("${jedis.pool.host}")String host,  
              @Value("${jedis.pool.port}")int port) { 
      return new JedisPool(config, host, port); 
  } 
     
  @Bean(name= "jedis.pool.config") 
  public JedisPoolConfig jedisPoolConfig (@Value("${jedis.pool.config.maxTotal}")int maxTotal, 
                              @Value("${jedis.pool.config.maxIdle}")int maxIdle, 
                              @Value("${jedis.pool.config.maxWaitMillis}")int maxWaitMillis) { 
      JedisPoolConfig config = new JedisPoolConfig(); 
      config.setMaxTotal(maxTotal); 
      config.setMaxIdle(maxIdle); 
      config.setMaxWaitMillis(maxWaitMillis); 
      return config; 
  }
}

5.mybatis配置sql

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
 * 初始化SqlSessionFactory
 * @ClassName MybatisConfiguration
 * @author Zhang.Tao
 * @Date 2017年4月24日 下午5:24:56
 * @version V2.0.0
 */
@Configuration
@ConditionalOnClass({ EnableTransactionManagement.class, EntityManager.class })
@AutoConfigureAfter({ DataBaseConfiguration.class })
public class MybatisConfiguration implements EnvironmentAware {
    private static Log logger = LogFactory.getLog(MybatisConfiguration.class);
    private RelaxedPropertyResolver propertyResolver;
    @Resource(name = "dataSource")
    DataSource dataSource;
    @Override
    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment,"mybatis.");
    }
    /**
     * 初始化SessionFactory
     * @Description TODO
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public SqlSessionFactory sqlSessionFactory() {
        try {
             
            System.err.println(propertyResolver.getProperty("mapperLocations"));
            SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
            sessionFactory.setDataSource(dataSource);
            sessionFactory.setTypeAliasesPackage(propertyResolver
                    .getProperty("typeAliasesPackage"));
            sessionFactory
                    .setMapperLocations(new PathMatchingResourcePatternResolver()
                            .getResources(propertyResolver
                                    .getProperty("mapperLocations")));
            sessionFactory
                    .setConfigLocation(new DefaultResourceLoader()
                            .getResource(propertyResolver
                                    .getProperty("configLocation")));
            return sessionFactory.getObject();
        } catch (Exception e) {
            e.printStackTrace();
            logger.warn("Could not confiure mybatis session factory");
            return null;
        }
    }
    @Bean
    @ConditionalOnMissingBean
    public DataSourceTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}

6.MyBatis配置文件(這個和Spring不要緊,是mybatis的,必須寫沒毛病啊,老鐵)數據庫

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties>
        <property name="dialect" value="mysql" />
    </properties>
    <settings>
        <!-- 這個配置使全局的映射器啓用或禁用緩存。系統默認值是true,設置只是爲了展現出來 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局啓用或禁用延遲加載。當禁用時,全部關聯對象都會即時加載。 系統默認值是true,設置只是爲了展現出來 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 容許或不容許多種結果集從一個單獨的語句中返回(須要適合的驅動)。 系統默認值是true,設置只是爲了展現出來 -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--使用列標籤代替列名。不一樣的驅動在這方便表現不一樣。參考驅動文檔或充分測試兩種方法來決定所使用的驅動。 系統默認值是true,設置只是爲了展現出來 -->
        <setting name="useColumnLabel" value="true" />
        <!--容許 JDBC 支持生成的鍵。須要適合的驅動。若是設置爲 true 則這個設置強制生成的鍵被使用,儘管一些驅動拒絕兼容但仍然有效(好比
            Derby)。 系統默認值是false,設置只是爲了展現出來 -->
        <setting name="useGeneratedKeys" value="false" />
        <!--配置默認的執行器。SIMPLE 執行器沒有什麼特別之處。REUSE 執行器重用預處理語句。BATCH 執行器重用語句和批量更新 系統默認值是SIMPLE,設置只是爲了展現出來 -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--設置超時時間,它決定驅動等待一個數據庫響應的時間。 系統默認值是null,設置只是爲了展現出來 -->
        <setting name="defaultStatementTimeout" value="25000" />
    </settings>
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageHelper">
            <property name="dialect" value="mysql" />
            <property name="offsetAsPageNum" value="true" />
            <property name="rowBoundsWithCount" value="true" />
            <property name="pageSizeZero" value="true" />
            <property name="reasonable" value="true" />
        </plugin>
    </plugins>
</configuration>

7.API接口代碼(是否是很6,想不想贊一下?)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.tony.spring.boot.entity.UserInfo;
import com.tony.spring.boot.mapper.UserInfoMapper;
import com.tony.spring.boot.utils.JsonUtil;
import com.tony.spring.boot.utils.RedisUtil;
/**
 * Created by Administrator on 2017/4/19.
 */
@RestController
@RequestMapping(value="/test")
public class TestCtrl {
     
    @Autowired
    private RedisUtil redisUtil;
     
    @Autowired 
    private UserInfoMapper userInfoMapper; 
    @RequestMapping(value="/index")
    public String index(){
        return "hello world";
    }
     
    /**
     * 向redis存儲值
     * @param key
     * @param value
     * @return
     * @throws Exception
     */
    @RequestMapping("/set") 
    public String set(String key, String value) throws Exception{ 
        redisUtil.set(key, value); 
        return "success"; 
    } 
     
    /**
     * 獲取redis中的值
     * @param key
     * @return
     */
    @RequestMapping("/get") 
    public String get(String key){ 
        try {
            return redisUtil.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ""; 
    } 
     
    /**
     * 獲取數據庫中的用戶
     * @Description TODO
     * @param id
     * @return
     */
    @RequestMapping("/getUser/{id}") 
    public String get(@PathVariable("id")int id){ 
        try {
            System.err.println(id);
            UserInfo user= userInfoMapper.selectByPrimaryKey(id);
            return JsonUtil.getJsonString(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ""; 
    } 
}

8.到這裏基本上核心的東西差很少了,去Application.java啓動就能用了。趕快試試吧

相關文章
相關標籤/搜索