Spring底層框架搭建步驟
阿新 • • 發佈:2022-04-09
Spring底層框架搭建步驟
1、建立資料庫
CREATE DATABASE [IF NOT EXISTS] <資料庫名> [[DEFAULT] CHARACTER SET <字符集名>] [[DEFAULT] COLLATE <校對規則名>]; [ ]中的內容是可選的。語法說明如下: <資料庫名>:建立資料庫的名稱。MySQL 的資料儲存區將以目錄方式表示 MySQL 資料庫,因此資料庫名稱必須符合作業系統的資料夾命名規則,不能以數字開頭,儘量要有實際意義。注意在 MySQL 中不區分大小寫。 IF NOT EXISTS:在建立資料庫之前進行判斷,只有該資料庫目前尚不存在時才能執行操作。此選項可以用來避免資料庫已經存在而重複建立的錯誤。 [DEFAULT] CHARACTER SET:指定資料庫的字符集。指定字符集的目的是為了避免在資料庫中儲存的資料出現亂碼的情況。如果在建立資料庫時不指定字符集,那麼就使用系統的預設字符集。 [DEFAULT] COLLATE:指定字符集的預設校對規則。 CREATE TABLE table_name ( column_name column_type NOT NULL AUTO_INCREMENT PRIMARY KEY )ENGINE=INNODB DEFAULT CHARSET=utf8 如果你不想欄位為 NULL 可以設定欄位的屬性為 NOT NULL, 在操作資料庫時如果輸入該欄位的資料為NULL ,就會報錯。 AUTO_INCREMENT定義列為自增的屬性,一般用於主鍵,數值會自動加1。 PRIMARY KEY關鍵字用於定義列為主鍵。 您可以使用多列來定義主鍵,列間以逗號分隔。 ENGINE 設定儲存引擎,CHARSET 設定編碼。 INSERT INTO table_name ( field1, field2,...fieldN ) VALUES ( value1, value2,...valueN ); DELETE FROM table_name [WHERE Clause] SELECT column_name,column_name FROM table_name [WHERE Clause] [LIMIT N][ OFFSET M] UPDATE table_name SET field1=new-value1, field2=new-value2[WHERE Clause]
2、建立maven專案
3、建立專案資料夾
4、匯入依賴
<dependencies> <!--Junit單元測試--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!--資料庫驅動--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.27</version> </dependency> <!-- 資料庫連線池 --> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--Servlet - JSP --> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--Mybatis--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.5.9</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>2.0.7</version> </dependency> <!--Spring--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.3.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>5.3.12</version> </dependency> <!--aop--> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.7</version> </dependency> <!--註解驅動--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.10</version> </dependency> </dependencies>
<!-- 靜態資源匯出過濾--> <build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build>
5、配置資料庫外部配置檔案 db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssmbuild?useUnicode=true&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC
jdbc.username=root
jdbc.password=jzyctbu09.@
#注意點
#mysql-connector-java 6.0.x 以下版本如果要指定mysql的時區,需要新增以下引數 &useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
#而在mysql-connector-java 6.0.x 及以上版本,serverTimezone引數為必填項,必須指定
#useUnicode=true&characterEncoding=UTF-8
#useUnicode=true&characterEncoding=UTF-8表示此連線的 mysql 客戶端資料為 UTF-8,mysql伺服器則是任意編碼,如果mysql服務#器也是 UTF-8 編碼,則可以不寫。
#假如 mysql 資料庫用的是 gbk 編碼,而專案用的是 utf-8 編碼。這時候如果添加了useUnicode=true&characterEncoding=UTF-8 ,#那麼
#存資料時:會先用UTF-8格式將資料解碼成位元組碼,然後再將解碼後的位元組碼重新使用GBK編碼存放到資料庫中。
#取資料時:先將資料庫中的資料按GBK格式解碼成位元組碼,然後再將解碼後的位元組碼重新按UTF-8格式編碼
#serverTimezone
#serverTimezone=Asia/Shanghai表示此連線的 mysql 客戶端的時區為Asia/Shanghai,通過此連線傳輸的時間的時區都為#Asia/Shanghai
#serverTimezone引數主要用在 mysql 客戶端和 mysql 伺服器在不同時區時,轉換二者互動中時間資料。
#例如: mysql 客戶端位於中國,時區為 UTC+08:00(北京)。mysql 伺服器部署在美國加州,時區為 UTC-08:00 (美國加州)。現在客戶端有一條記錄的建立時間是北京時區時間22:00,當資料儲存到資料庫時,建立時間的時區會轉換成資料庫對應的時區,因此資料庫實際儲存的建立時間為 06:00。 當 mysql 客戶端讀取到這條記錄時,伺服器根據自己的時區和客戶端連線設定的時區,將儲存的 06:00 轉成 22:00 返回給客戶端
6、配置mybatis基礎配置檔案 mybatis-config.xml
<?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>
<!-- 設定日誌輸出,可以看到sql語句是怎樣的,資料庫查詢結果是怎樣的等等-->
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!-- 給實體類設定別名-->
<typeAliases>
<!-- 別名為實體類名稱首字母小寫-->
<package name="com.jiang.pojo"/>
<!-- 別名為自定義的-->
<typeAlias type="com.jiang.dao.User" alias="User"/>
</typeAliases>
<!--註冊mapper四種方式 -->
<mappers>
<mapper resource="com/jiang/dao/BookMapper.xml"/>
<package name="org.mybatis.builder"/>
<mapper class="org.mybatis.builder.BlogMapper"/>
<mapper url="file:///var/mappers/BlogMapper.xml"/>
</mappers>
</configuration>
<!--mybatis-config.xml標頭檔案 -->
<!--mybatis-config.xml檔案順序properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers? -->
7、配置mapper對映檔案
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--指定名稱空間-->
<mapper namespace="com.jiang.dao.BookMapper">
<!--寫sql了語句-->
</mapper>
<!--mapper的標頭檔案-->
8、配置spring-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!-- 配置整合mybatis -->
<!-- 1.關聯資料庫檔案 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 2.資料庫連線池 -->
<!--資料庫連線池
dbcp 半自動化操作 不能自動連線
c3p0 自動化操作(自動的載入配置檔案 並且設定到物件裡面)
-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 配置連線池屬性 -->
<property name="driverClass" value="${jdbc.driver}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- c3p0連線池的私有屬性 -->
<property name="maxPoolSize" value="30"/>
<property name="minPoolSize" value="10"/>
<!-- 關閉連線後不自動commit -->
<property name="autoCommitOnClose" value="false"/>
<!-- 獲取連線超時時間 -->
<property name="checkoutTimeout" value="10000"/>
<!-- 當獲取連線失敗重試次數 -->
<property name="acquireRetryAttempts" value="2"/>
</bean>
<!-- 3.配置SqlSessionFactory物件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource"/>
<!-- 配置MyBaties全域性配置檔案:mybatis-config.xml -->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
</bean>
<!-- 4.配置掃描Dao介面包,動態實現Dao介面注入到spring容器中 -->
<!--解釋 :https://www.cnblogs.com/jpfss/p/7799806.html-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 注入sqlSessionFactory -->
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<!-- 給出需要掃描Dao介面包 -->
<property name="basePackage" value="com.jiang.dao"/>
</beans>
在Java中開源的資料庫連線池有以下幾種 :
C3P0:是一個開放原始碼的JDBC連線池,它在lib目錄中與Hibernate一起釋出,包括了實現jdbc3和jdbc2擴充套件規範說明的Connection 和Statement 池的DataSources 物件。
Druid:Druid不僅是一個數據庫連線池,還包含一個ProxyDriver、一系列內建的JDBC元件庫、一個SQL Parser。支援所有JDBC相容的資料庫,包括Oracle、MySql、Derby、Postgresql、SQL Server、H2等。
Proxool:是一個Java SQL Driver驅動程式,提供了對選擇的其它型別的驅動程式的連線池封裝。可以非常簡單的移植到現存的程式碼中,完全可配置,快速、成熟、健壯。可以透明地為現存的JDBC驅動程式增加連線池功能。
DBCP:DBCP是一個依賴Jakarta commons-pool物件池機制的資料庫連線池,DBCP可以直接的在應用程式中使用,Tomcat的資料來源使用的就是DBCP。
我們在使用連線池時,連線池給我們提供了獲取資料庫連線的方法,但使用完成後還是要呼叫 close 方法來關閉連線。但是實際上使用連線池時呼叫 close() 方法實際上並沒有關閉連線,只是將該連線歸還給連線池。
9、配置spring-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 掃描service相關的bean -->
<context:component-scan base-package="com.jiang.service" />
<!--BookServiceImpl注入到IOC容器中-->
<bean id="BookServiceImpl" class="com.jiang.service.BookServiceImpl">
<property name="bookMapper" ref="bookMapper"/>
</bean>
<!-- 配置事務管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 注入資料庫連線池 -->
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
10、配置spring-mvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置SpringMVC -->
<!-- 1.開啟SpringMVC註解驅動 -->
<mvc:annotation-driven />
<!-- 2.靜態資源預設servlet配置-->
<mvc:default-servlet-handler/>
<!-- 3.配置jsp 顯示ViewResolver檢視解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
<!--字首-->
<property name="prefix" value="/WEB-INF/jsp/" />
<!--字尾-->
<property name="suffix" value=".jsp" />
<!--將controller返回的字串拼str接在一起 /WEB-INF/jsp/str.jsp-->
</bean>
<!-- 4.掃描web相關的bean -->
<context:component-scan base-package="com.jiang.controller" />
</beans>
11、配置applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--將其他檔案引入spring整合檔案,另外在配置上下文時,都選spring整合檔案-->
<import resource="spring-dao.xml"/>
<import resource="spring-service.xml"/>
<import resource="spring-mvc.xml"/>
</beans>
11、配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!--一定要是spring整合檔案-->
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<!--啟動級別-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 亂碼過濾-->
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- session過期時間-->
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>
< url-pattern > / < url-pattern >
/* 能匹配所有請求URL,會匹配到*.jsp,會出現返回jsp檢視時再次進入spring的DispatcherServlet 類,導致找不到對應的controller所以報404錯.
當對映規則為 /* 時,最後返回xx.jsp也經過DispatcherServlet,它又會去找相對應的處理器,這也是控制檯列印noHandlerFound,也就導致了404錯誤,頁面更別想看到。當改成 / 後,servlet不會匹配到.jsp的URI,當然就能正常返回頁面了
12、配置中央控制器(controller)
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
/*
@Autowired 註釋,它可以對類成員變數、方法及建構函式進行標註,完成自動裝配的工作。 通過 @Autowired的使用來消除 set ,get方法。
使用 @Autowired 註解是 Spring 依賴注入的絕好方法。但是有些場景下僅僅靠這個註解不足以讓Spring知道到底要注入哪個 bean。預設情況下,@Autowired 按型別裝配 Spring Bean。如果容器中有多個相同型別的 bean,則框架將丟擲 NoUniqueBeanDefinitionException, 以提示有多個滿足條件的 bean 進行自動裝配。程式無法正確做出判斷使用哪一個
通過將 @Qualifier 註解與我們想要使用的特定 Spring bean 的名稱一起進行裝配,Spring 框架就能從多個相同型別並滿足裝配要求的 bean 中找到我們想要的,避免讓Spring腦裂。我們需要做的是@Component或者@Bean註解中宣告的value屬性以確定名稱
*/
@Qualifier("BookServiceImpl")
private BookService bookService;
@RequestMapping("/allBook")
public String list(Model model) {
List<Books> list = bookService.queryAllBook();
model.addAttribute("list", list);
return "allBook";
}
}
自己做了一點總結,歡迎各位大佬們指出我的不足!