教你十分鐘構建好 SpringBoot + SSM 框架

目前最主流的 java web 框架應該是 SSM,而 SSM 框架因爲更輕便與靈活目前受到了許多人的青睞。而 SpringBoot 的輕量化,簡化項目配置, 沒有 XML 配置要求等優勢如今也獲得了大衆的青睞java

而本文,我將教你們如何在 intellij idea 中快速構建好一個 Maven + Spring + SpringMVC + MyBatis + SpringBoot 的框架,作到了足夠精簡,讓你能夠馬上開始你的 web 項目mysql

附上這個簡單的框架構建的 github 地址 SSM-SpringBootgit

一. 建立項目

選擇 Spring Initiallizrgithub

image

添加最基本的幾個依賴 Web,MySQL,MyBatis,其餘需求能夠後續再添加 ; 數據庫選擇了 MySQLweb

二. 配置數據源

數據源中存儲了全部創建數據庫鏈接的信息redis

1. 配置 IDEA 數據源

輸入地址,端口,用戶名,密碼等等完成設置 spring

2. 配置 spring 數據源

application.properties 文件添加:sql

spring.datasource.url = jdbc:mysql://xx.xx.xx.x:xxx/xxx?characterEncoding=utf8&allowMultiQueries=true&useSSL=false
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
複製代碼
  • url : 數據源 url ,格式爲 jdbc:mysql://Host(主機名或 IP 地址):Post(端口)/Database(數據庫名稱),其中 allowMultiQueries = true : 容許多條 sql 同時執行(分號分隔);useSSL : 是否進行 SSL 鏈接,根據實際狀況選擇
  • username : 用戶名
  • password : 密碼
  • driver-class-name : 驅動名,不一樣的數據庫有不一樣的 Drivername,如 oracle 數據庫的 oracle.jdbc.driver.OracleDriver,MySQL 數據庫爲 com.mysql.jdbc.Driver

三. Spring 註解

  • 使用 @Controller / @RestController 註解標註一個控制器,代表這個類是做爲控制器的角色而存在的
  • 使用 @Service 註解標註一個業務層類
  • 使用 @Repository 註解標註一個持久層 mapper 接口
  • 使用 @Component 註解標註其餘組件
  • 使用 @Configuration 註解標註配置類

四. MyBatis

整個項目的構建最主要的部分就是 springboot 和 mybatis 的整合,而 springboot 也提供了十分方便的方式。數據庫

1. xml 文件

  • 聲明爲映射文件
  • namespace : 指該映射文件對應的映射接口 ; 通常來講,一個 XML 映射配置文件對應一個命名空間,而這個命名空間又對應一個接 口
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.swit.dao.MyMapper">

</mapper>
複製代碼

2. application.properties

  • Mybatis 配置,指定了 mybatis 基礎配置文件和實體類映射文件的地址
mybatis.mapperLocations = classpath:mapper/**/*.xml
mybatis.typeAliasesPackage = com.swit.model
複製代碼
  • 配置 typeAliasesPackage 能夠使得 com.swit.model 包內的實體類能夠在映射文件中使用別名,如:
<select id="getUser" parameterType="int" resultType="User">

</select>
複製代碼

如沒有配置 typeAliasesPackage ,則須要 resultType="com.swit.model.User"apache

  • 若是要對 MyBatis 經過 xml 文件進行另外的配置,則添加文件路徑:
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
複製代碼

3. 添加對 mapper 類的掃描

如下兩種方法二選其一

(1)能夠選擇在啓動類添加 @MapperScan

value 爲 mapper 類所在的包(注意這裏是包的路徑,而不是類的路徑!)

@MapperScan(value = "com.swit.dao")
複製代碼

另外, @MapperScan 註解面向的是接口類,只要是加了註解的接口類都須要進行經過該註解來掃描

(2)能夠在每一個 mapper 類上添加 @mapper 註解

@Mapper
@Repository
public interface MyMapper {
}
複製代碼

到目前爲止,你已經完成了你的項目的構建,下面我還會介紹些別的東西。

五. 其餘要注意的點

1. @SpringBootApplication

  • 這個註解位於啓動類
  • @SpringBootApplication 等價於以默認屬性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan, 因此啓動類無需再添加這三個註解
  • @Configuration :標註一個類爲配置類。
  • @EnableAutoConfiguration :開啓自動配置。
  • @ComponentScan :自動收集全部的 Spring 組件

2. 部署服務器

若是你想把本身的 SpringBoot 項目部署到阿里雲,騰訊雲等服務器,那麼你還須要加點東西。 1.若是須要經過打包的方式在web容器中進行部署,則須要繼承 SpringBootServletInitializer 覆蓋configure(SpringApplicationBuilder)方法

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

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        // 注意這裏要指向原先用main方法執行的Application啓動類
        return builder.sources(SpringbootApplication.class);
    } 
}
複製代碼

2.pom 文件添加打包插件

<build>
        <!--打包後的項目名,url 前綴-->
		<finalName>projectName</finalName>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<!--設置編譯時使用的 JDK 版本-->
					<source>1.8</source>
					<!--設置運行時使用的 JDK 版本-->
					<target>1.8</target>
					<!--設置爲 true 則跳過測試-->
					<skip>true</skip>
				</configuration>
			</plugin>
		</plugins>
	</build>
複製代碼
  1. 你頗有可能還須要作個跨域處理
@Component
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", Origin);
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, " + this.tokenHeader);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void destroy() {
    }
}
複製代碼

六. 整合其餘組件

1. redis

redis 也是咱們項目中常常用到的 NoSQL,常常用來作作緩存什麼的。

依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
複製代碼

application.properties

# Redis數據庫索引(默認爲0)
spring.redis.database=0
# Redis服務器地址
spring.redis.host=127.0.0.1
# Redis服務器鏈接端口
spring.redis.port=6379
# Redis服務器鏈接密碼(默認爲空)
spring.redis.password=123456
# 鏈接池最大鏈接數(使用負值表示沒有限制)
spring.redis.pool.max-active=15
# 鏈接池最大阻塞等待時間(使用負值表示沒有限制)
spring.redis.pool.max-wait=-1
# 鏈接池中的最大空閒鏈接
spring.redis.pool.max-idle=15
# 鏈接池中的最小空閒鏈接
spring.redis.pool.min-idle=0
# 鏈接超時時間(毫秒)
spring.redis.timeout=0
複製代碼

2. Druid 數據源

針對監控而生的 DB 鏈接池

依賴

<dependency>
       <groupId>com.alibaba</groupId>
       <artifactId>druid</artifactId>
       <version>1.0.20</version>
</dependency>
複製代碼

application.properties

spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.filters=stat
spring.datasource.maxActive=20
spring.datasource.initialSize=5
spring.datasource.maxWait=60000
spring.datasource.minIdle=1
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 'x'
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxOpenPreparedStatements=20
複製代碼

你的關注是我寫博客最大的動力~

猜你喜歡 :

相關文章
相關標籤/搜索