SpringMVC配置太多?试试SpringBoot

栏目: Java · 发布时间: 7年前

内容简介: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文件。

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启动

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 数据源

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数据源配置.

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数据源
 * Java Lib For OIS, Powered By BeiJing FanTongTianXia.
 * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd
 * http://www.chifaner.com/
 *
 * @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配置

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
 * Java Lib For OIS, Powered By BeiJing FanTongTianXia.
 * Copyright (c) 2014-2017 FanTongTianXia Co.,Ltd
 * http://www.chifaner.com/
 *
 * @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启动就能用了。赶快试试吧


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

复盘+:把经验转化为能力(第2版)

复盘+:把经验转化为能力(第2版)

邱昭良 / 机械工业出版社 / 39.00

随着环境日趋多变、不确定、复杂、模糊,无论是个人还是组织,都需要更快更有效地进行创新应变、提升能力。复盘作为一种从经验中学习的结构化方法,满足了快速学习的需求,也是有效进行知识萃取与共享的机制。在第1版基础上,《复盘+:把经验转化为能力》(第2版)做了六方面修订: ·提炼复盘的关键词,让大家更精准地理解复盘的精髓; ·基于实际操作经验,梳理、明确了复盘的"底层逻辑"; ·明确了复......一起来看看 《复盘+:把经验转化为能力(第2版)》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换