1. 程式人生 > >springboot+mybatis+springMVC基礎框架搭建

springboot+mybatis+springMVC基礎框架搭建

mvc adapter scan 編譯插件 java extend -m npr 初始化

項目結構概覽

技術分享圖片

技術分享圖片

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!-- springboot依賴的父類 -->
    <
parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> </parent> <!-- 項目骨架 --> <groupId>com.pupeiyuan</groupId> <artifactId
>ssm-springboot</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <!-- 指定一下jdk的版本 ,這裏我們使用jdk 1.8 ,默認是1.6 --> <
java.version>1.8</java.version> </properties> <dependencies> <!-- 單元測試 --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> <!-- 支持springWEB web支持: 1、web mvc; 2、restful; 3、jackjson支持; 4、aop ........ --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <!-- Mybatis --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <!-- 通用Mapper --> <dependency> <groupId>tk.mybatis</groupId> <artifactId>mapper-spring-boot-starter</artifactId> <version>RELEASE</version> </dependency> <!-- 分頁助手 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.1.0</version> </dependency> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>0.9.1</version> </dependency> <!-- mysql 數據庫驅動. --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- 連接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.9</version> </dependency> <!-- jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- JSP相關 --> <dependency> <groupId>com.github.jsqlparser</groupId> <artifactId>jsqlparser</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> <!-- httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> </dependencies> <build> <plugins> <!-- java編譯插件 --> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

application.properties

spring.profiles.active=test

application-test.properties

#datasource -- mysql
jdbc.url=jdbc:mysql://localhost:3306/test1?useUnicode=true&characterEncoding=utf8&autoReconnect=true&allowMultiQueries=true
jdbc.username=root
jdbc.password=pypua
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.InitialSize=10
jdbc.MinIdle=10
jdbc.MaxActive=100

#Tomcat
server.port=8082
server.servlet-path=/

#log4j
#logging.level.org.springframework=DEBUG

#SpringMVC
spring.mvc.view.prefix=/WEB-INF/views/
spring.mvc.view.suffix=.jsp

#mybatis && Mapper
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.configuration.mapUnderscoreToCamelCase=true
mapper.mappers=com.karle.tk.TkMapper
mapper.identity=MYSQL

#banner
banner.charset= UTF-8

#jsp
server.jsp-servlet.init-parameters.development=true

# pagehelper properties
pagehelper.offsetAsPageNum=true
pagehelper.rowBoundsWithCount=true
pagehelper.pageSizeZero=true
pagehelper.reasonable=false
pagehelper.params=pageNum=pageHelperStart;pageSize=pageHelperRows;
pagehelper.supportMethodsArguments=false

main.java

package com.pupeiyuan;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import com.pupeiyuan.config.MainApplication;

/**
 * Springboot啟動類
 * @author Administrator
 *
 */

public class main {
    
    public static void main(String[] args) {
        SpringApplication.run(MainApplication.class, args);
    }
}

MainApplication.java

package com.pupeiyuan.config;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import com.alibaba.druid.pool.DruidDataSource;

@Configuration
//掃描bean
@ComponentScan(basePackages = "com.pupeiyuan.*")
//不用自動配置數據源
@SpringBootApplication(exclude=DataSourceAutoConfiguration.class)
public class MainApplication extends SpringBootServletInitializer {

    @Value("${jdbc.url}")
    private String jdbcUrl;

    @Value("${jdbc.driverClassName}")
    private String jdbcDriverClassName;

    @Value("${jdbc.username}")
    private String jdbcUsername;

    @Value("${jdbc.password}")
    private String jdbcPassword;
    
    @Value("${jdbc.InitialSize}")
    private int InitialSize;
    
    @Value("${jdbc.MinIdle}")
    private int MinIdle;
    
    @Value("${jdbc.MaxActive}")
    private int MaxActive;

    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        // BoneCPDataSource boneCPDataSource = new BoneCPDataSource();
        DruidDataSource druidDataSource = new DruidDataSource();
        // 數據庫驅動
        druidDataSource.setDriverClassName(jdbcDriverClassName);
        // 相應驅動的jdbcUrl
        druidDataSource.setUrl(jdbcUrl);
        // 數據庫的用戶名
        druidDataSource.setUsername(jdbcUsername);
        // 數據庫的密碼
        druidDataSource.setPassword(jdbcPassword);
        // 檢查數據庫連接池中空閑連接的間隔時間,單位是分,默認值:240,如果要取消則設置為0
        // 初始化時建立物理連接的個數
        druidDataSource.setInitialSize(InitialSize);
        // 最小連接池數量
        druidDataSource.setMinIdle(MinIdle);
        // 最大連接池數量
        druidDataSource.setMaxActive(MaxActive);

        //配置監控統計攔截的filters,去掉後監控界面sql無法統計,‘wall‘用於防火墻
        try {
            druidDataSource.setFilters("stat,wall,log4j");
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    
        // 通過connectProperties屬性來打開mergeSql功能;慢SQL記錄
        druidDataSource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");
        //合並多個DruidDataSource的監控數據
        druidDataSource.setUseGlobalDataSourceStat(true);
        return druidDataSource;
    }

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

MybatisConfig.java

package com.pupeiyuan.config;

import java.util.Properties;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import com.github.pagehelper.PageHelper;

import tk.mybatis.spring.annotation.MapperScan;
import tk.mybatis.spring.mapper.MapperScannerConfigurer;

@Configuration
@MapperScan("com.pupeiyuan.mapper")
public class MyBatisConfig {

    @Autowired
    private DataSource dataSource;

    @Bean
    @ConditionalOnMissingBean // 當容器裏沒有指定的Bean的情況下創建該對象
    public SqlSessionFactoryBean sqlSessionFactoryBean() {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 設置數據源
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 設置別名包
        sqlSessionFactoryBean.setTypeAliasesPackage("com.pupeiyuan.bean");

        return sqlSessionFactoryBean;
    }
    
}

SpringMVCConfig.java

package com.pupeiyuan.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.pupeiyuan.interceptors.IsLoginHandlerInterceptor;

@Configuration
public class SpringMVCConfig extends WebMvcConfigurerAdapter{

    @Autowired
    private IsLoginHandlerInterceptor isLoginHandlerInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 判斷用戶是否登錄的攔截器
        registry.addInterceptor(isLoginHandlerInterceptor).addPathPatterns("/burket/**");
    }
}

DruidConfiguration.java

package com.pupeiyuan.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfiguration {

    /**
     * 註冊一個StatViewServlet
     * 
     * @return
     */
    @Bean
    public ServletRegistrationBean DruidStatViewServle2() {
        // org.springframework.boot.context.embedded.ServletRegistrationBean提供類的進行註冊.
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),
                "/druid/*");
        // 添加初始化參數:initParams
        // 白名單:
        servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
        // IP黑名單 (存在共同時,deny優先於allow) : 如果滿足deny的話提示:Sorry, you are not
        // permitted to view this page.
        servletRegistrationBean.addInitParameter("deny", "192.168.1.73");
        // 登錄查看信息的賬號密碼.
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "123456");
        // 是否能夠重置數據.
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 註冊一個:filterRegistrationBean
     * 
     * @return
     */
    @Bean
    public FilterRegistrationBean druidStatFilter2() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        // 添加過濾規則.
        filterRegistrationBean.addUrlPatterns("/*");
        // 添加不需要忽略的格式信息.
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}

springboot+mybatis+springMVC基礎框架搭建