Too many Spring MVC configurations? Try Spring Boot

Keywords: Java Spring Mybatis Jedis Redis

Spring MVC believes that you are no longer unfamiliar, you may have a disgusting feeling about Spring's various XML configurations. Spring's official Spring boot has been published for a long time. Spring boot is a lightweight framework of "convention is better than configuration". Spring boot first solves all kinds of tedious XML configurations, you can do web services without any XML configuration. Build, followed by Springboot itself inherited the web server, if the front-end developers want to start the back-end services locally without various configurations, can almost do a one-click start.

Then there is the current hot micro-services, and Springboot just meets the rapid development of micro-services development scenario; for the current mainstream framework Spring+MyBatis+redis integration, let's look directly at the code.

The following code is the integration of the entire development framework. I will not explain how Spring's official set of startup classes are written and how to configure ports, which are a handful of random google. The following code, mybatis mapper I will not post, how to write now is the same as usual, and redis storage data to fetch data and so on. What this article gives is the key point of drawing.

1. Data source and other configuration files (PS: Say no configuration, how to configure it at the beginning? Answer: It's okay not to configure it, if you want to hard-code the data source to death. (3)

The following is the configuration file of YML, which is supported by various mainstream development languages, equivalent to common. properties files.

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
        # Using druid data source
        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 Start

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;//Application Port
    /**
     * Start the entrance
     * @param args
     */
    public static void main(String ... args){
        SpringApplication.run(Application.class, args);
    }
    /**
     * Custom Port
     */
    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {
        container.setPort(port);       
    }
}

3. Configure Mysql data source

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.");
    }
    /**
     * Configuring data sources
     * @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"));//User name 
         dataSource.setPassword(propertyResolver.getProperty("password"));//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 data source configuration.

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;
/**
 * Configure redis data source
 * 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 April 24, 2000, 5:25:30 p.m.
 * @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 configuration

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;
/**
 * Initialize 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 April 24, 2000, 5:24:56 p.m.
 * @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.");
    }
    /**
     * Initialize 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 configuration file (this is not related to Spring, it's mybatis. It must be written, no problem, old iron).

<?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>
        <!-- This configuration enables global mappers to enable or disable caching. The default value of the system is true,Setting up just to show off -->
        <setting name="cacheEnabled" value="true" />
        <!-- Globally enable or disable lazy loading. When disabled, all associated objects are loaded immediately. The default value of the system is true,Setting up just to show off -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- Multiple result sets are allowed or not to be returned from a single statement (requiring appropriate drivers). The default value of the system is true,Setting up just to show off -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!--Use column labels instead of column names. Different drivers behave differently in this convenience. Reference to driver documentation or adequate testing are two ways to determine the driver used. The default value of the system is true,Setting up just to show off -->
        <setting name="useColumnLabel" value="true" />
        <!--allow JDBC Support generated keys. A suitable driver is needed. If set to true This setting forces the generated keys to be used, although some drivers refuse compatibility, they are still valid (e.g.
            Derby).  The default value of the system is false,Setting up just to show off -->
        <setting name="useGeneratedKeys" value="false" />
        <!--Configure the default executor. SIMPLE There is nothing special about the actuator. REUSE The executor reuses the preprocessing statement. BATCH Executor reuse statements and batch update system defaults are SIMPLE,Setting up just to show off -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!--Set a timeout, which determines the time the driver waits for a database response. The default value of the system is null,Setting up just to show off -->
        <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 interface code (is it very 6, would you like to praise it?)?

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";
    }
     
    /**
     * Storing values to 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"; 
    } 
     
    /**
     * Get the value in redis
     * @param key
     * @return
     */
    @RequestMapping("/get") 
    public String get(String key){ 
        try {
            return redisUtil.get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ""; 
    } 
     
    /**
     * Getting users in the database
     * @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. It's almost the core thing here, and it's ready to start with Application.java. Give it a try.

Posted by mclamais on Tue, 25 Jun 2019 17:06:13 -0700