Integrated configuration of SpringBoot+Mybatis+PageHelper+logback+Swagger+Maven

Integrated configuration of SpringBoot+Mybatis+PageHelper+logback+Swagger+Maven

Microservices have become a hot topic now, and the Pivotal team provides this framework to save time and realize simple development, because it integrates many frameworks by default (of course, you can explore it yourself or check the official document: spring.io/projects/sp... And Mybatis uses the Druid data source provided by Ali as the data layer, PageHelper is used for paging, lomback is used as log output, and Swagger is used to generate Restful API interface documents (disadvantages: intrusive code, not very friendly), personal feeling is still It's pretty easy to use.

logback, mybatis, pagehelper configuration

logging:
    level:
    com.test: ERROR
    config: classpath:logback.xml
    path:/
spring:
    application:
    name:  
    boot:
        admin:
            url: http://localhost:3306
    datasource:
        name: test
        url: jdbc:mysql://:3306/?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=round&allowMultiQueries=true
        username: root
        password:  
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat,wall
        # 
        maxActive: 20
        # 
        initialSize: 5
        # 1 
        maxWait: 60000
         # 5, 
         minIdle: 5
        #1.Destroy 
        #2.testWhileIdle 
        timeBetweenEvictionRunsMillis: 60000
         # 25200000 300000/1000/60 = 5 
        minEvictableIdleTimeMillis: 300000
         # 
        validationQuery: select 'x'
        # true 
         # timeBetweenEvictionRunsMillis validationQuery 
        testWhileIdle: true
         # 
        testOnBorrow: false
        # 
         testOnReturn: false
         poolPreparedStatements: true
        # PSCache 0 0 poolPreparedStatements true 
         # Druid Oracle PSCache 100
         maxOpenPreparedStatements: 20
         # true false 
        log-abandoned: true
         maxPoolPreparedStatementPerConnectionSize: 20
     http:
        encoding:
            charset: utf-8
            enabled: true
            force: true
server:
    port: 8090
# 
debug: true
 

1. Logback configuration

Create a new logback.xml file under the resource folder, and then the specific configuration is as follows:

<configuration scan="true" scanPeriod="60 seconds">
    <include resource="org/springframework/boot/logging/logback/base.xml"/>
    <logger name="org.springboot.sample" level="TRACE"/>
    <!--  + .  . -->
    <springProfile name="test,dev">
        <!--<logger name="org.springframework.web" level="INFO"/>-->
        <logger name="org.springboot.sample" level="DEBUGGER"/>
        <logger name=" com.test com.test" level="DEBUGGER"/>
    </springProfile>
    <!--  . -->
    <springProfile name="prod">
        <logger name="org.springboot.sample" level="ERROR"/>
        <logger name=" com.test com.test" level="ERROR"/>
    </springProfile>
    <!--<jmxConfigurator/>-->
</configuration>
 

2. Mybatis, pagehelper configuration

Create a new conf file under com.test, and create a new MybatisConfiguration class in the file. The specific configuration is as follows:

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
 
@Configuration
@MapperScan(basePackages = {"com.test.*.mapper"})
@EnableTransactionManagement(proxyTargetClass = true)
public class MybatisConfiguration {
 
    @Autowired
    WallFilter wallFilter;
 
    @Bean
    @ConfigurationProperties("spring.datasource")
    @Primary
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
       //filter
        List<Filter> filters = new ArrayList<>();
        filters.add(wallFilter);
        datasource.setProxyFilters(filters);
        return datasource;
    }
 
   /**
     *  sql 
     * @param wallConfig
     * @return
     */
    @Bean(name = "wallFilter")
    @DependsOn("wallConfig")
    public WallFilter wallFilter(WallConfig wallConfig){
        WallFilter wallFilter = new WallFilter();
        wallFilter.setConfig(wallConfig);
        return wallFilter;
    }
 
    @Bean(name = "wallConfig")
    public WallConfig wallConfig(){
        WallConfig wallConfig = new WallConfig();
       //
        wallConfig.setMultiStatementAllow(true);
       //
        wallConfig.setNoneBaseStatementAllow(true);
        return wallConfig;
    }
 
    @Bean
    @Primary
    public DataSourceTransactionManager dataSourceTransactionManager() {
        DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager();
        dataSourceTransactionManager.setDataSource(dataSource());
        return dataSourceTransactionManager;
    }
 
    @Bean
    @Primary
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        PagingPlugin pageHelper = new PagingPlugin();
        Properties properties = new Properties();
        properties.setProperty("reasonable", "true");
        properties.setProperty("supportMethodsArguments", "true");
        properties.setProperty("returnPageInfo", "check");
        properties.setProperty("params", "count=countSql");
        pageHelper.setProperties(properties);
        Interceptor[] plugins = new Interceptor[]{pageHelper};
        sessionFactory.setPlugins(plugins);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/**/*.xml"));
        return sessionFactory.getObject();
    }
}
 

Sagger configuration

Create a new Swagger2 class in the Application class, as follows:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;


@Configuration
@EnableSwagger2
public class Swagger2 {
    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
               //
                .apis(RequestHandlerSelectors.basePackage("com.test"))
                .paths(PathSelectors.any())
                .build();
    }

   /**
     *    api , 
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
               //
                .title(" ")
                .description("RestFul  ")
               //
//               .termsOfServiceUrl("")
                .contact(new Contact("zy", "", ""))
               //
                .version("1.0")
               //
                .build();
    }
}
 

springboot integrated fastjson

The control layer returns json processing, first inherit WebMvcConfigurerAdapter in the project Application class, and then rewrite the configureMessageConverters method

In this way, springboot and fastJson are integrated, and the control layer can be annotated (add @ResponseBody in the method or change @Controller to @RestController in the class) to return the object, and let springboot automatically process it as json.

springboot packaging

Create a new TestApp in the same level of Application, as follows:

import org.springframework.boot.builder.SpringApplicationBuilder;
public class TestApp extends org.springframework.boot.web.support.SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(FunctionAppuserApplication.class);
    }

}
 

Then you can use the maven package for packaging; well, according to the above, you can enjoy the springboot project! thank you all!