1. 程式人生 > >教你十分鐘構建好 SpringBoot + SSM 框架

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

控制器 默認 tid 持久 接口類 prepare color png intellij

目前最主流的 java web 框架應該是 SSM,而 SSM 框架由於更輕便與靈活目前受到了許多人的青睞。而 SpringBoot 的輕量化,簡化項目配置, 沒有 XML 配置要求等優點現在也得到了大眾的青睞。

而本文,我將教大家如何在 intellij idea 中快速構建好一個 Maven + Spring + SpringMVC + MyBatis + SpringBoot 的框架,做到了足夠精簡,讓你可以立刻開始你的 web 項目。
一. 創建項目

選擇 Spring Initiallizr
技術分享圖片

添加最基本的幾個依賴 Web,MySQL,MyBatis,其他需求可以後續再添加 ; 數據庫選擇了 MySQL

技術分享圖片
二. 配置數據源

數據源中存儲了所有建立數據庫連接的信息

  1. 配置 IDEA 數據源

輸入地址,端口,用戶名,密碼等等完成設置
技術分享圖片

  1. 配置 spring 數據源

application.properties 文件添加:

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>
  1. 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"

如果要對 MyBatis 通過 xml 文件進行另外的配置,則添加文件路徑:

mybatis.config-locations=classpath:mybatis/mybatis-config.xml
  1. 添加對 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 組件

  1. 部署服務器

如果你想把自己的 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>
  2. 你很有可能還需要做個跨域處理
@Component
public class CorsFilter implements Filter {
   /**
    * json web token 在請求頭的名字
    */
   private String tokenHeader = "X_Auth_Token";

   @Override
   public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
       HttpServletResponse response = (HttpServletResponse) res;
       HttpServletRequest request = (HttpServletRequest) req;
       String token = request.getHeader("X_Auth_Token");
       System.out.println(token + "token");
       String Origin = request.getHeader("Origin");
       System.out.println("Origin:" + Origin);
       System.out.println("tokenHeader:" + this.tokenHeader);
       Logger logger = Logger.getLogger(this.getClass());
       logger.info("Origin:  " + Origin);
       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
  1. 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

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