springboot+mybatis+thymeleaf 整合使用經驗分享

驅使你前進的不是恐懼就是誘惑。

                                      ----芽生三月

                                           20180512

----------------------------創建項目---

1.在線創建springboot項目



2.IDEA 創建springboot項目





----------------------------項目配置---

1.application.properties(個人喜好)

#server
server.port=8686
#dataSource
spring.datasource.url=jdbc:mysql://localhost:3306/doc
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=
spring.datasource.password=
#mapperLocation
mybatis.mapper-locations=classpath:/mapping/*.xml
#thymeleaf
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=false
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html

靜態資源處理:

By default, Spring Boot serves static content from a directory called /static (or /public or /resources or /META-INF/resources) in the classpath or from the root of the ServletContext. It uses the ResourceHttpRequestHandler from Spring MVC so that you can modify that behavior by adding your own WebMvcConfigurerand overriding the addResourceHandlers method.

In a stand-alone web application, the default servlet from the container is also enabled and acts as a fallback, serving content from the root of the ServletContext if Spring decides not to handle it. Most of the time, this does not happen (unless you modify the default MVC configuration), because Spring can always handle requests through the DispatcherServlet.

By default, resources are mapped on /**, but you can tune that with the spring.mvc.static-path-pattern property. For instance, relocating all resources to/resources/** can be achieved as follows:

spring.mvc.static-path-pattern=/resources/**


2. 註解

------no.1---------

Many Spring Boot developers like their apps to use auto-configuration, component scan and be able to define extra configuration on their "application class". A single@SpringBootApplication annotation can be used to enable those three features, that is:

The @SpringBootApplication annotation is equivalent to using @Configuration@EnableAutoConfiguration, and @ComponentScan with their default attributes, as shown in the following example:

package com.example.myapplication;

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

@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {

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

}
[Note]

@SpringBootApplication also provides aliases to customize the attributes of @EnableAutoConfiguration and @ComponentScan.

----no.2---------

@RestController
@RequestMapping(value="/users")
public class MyRestController {

	@RequestMapping(value="/{user}", method=RequestMethod.GET)
	public User getUser(@PathVariable Long user) {
		// ...
	}

	@RequestMapping(value="/{user}/customers", method=RequestMethod.GET)
	List<Customer> getUserCustomers(@PathVariable Long user) {
		// ...
	}

	@RequestMapping(value="/{user}", method=RequestMethod.DELETE)
	public User deleteUser(@PathVariable Long user) {
		// ...
	}}

----no.3---------

@RequestParam

The multipart support is helpful when you want to receive multipart encoded file data as a @RequestParam-annotated parameter of type MultipartFile in a Spring MVC controller handler method.

---------no.4-------
@Component
@ConfigurationProperties(prefix="acme")
將屬性文件以bean形式注入使用

待繼續學習----------

----------------------------項目開發---

1.根據組織架構創建package結構:分MVC三層,再每層分功能模塊。

2.根據功能模塊創建package結構:每個模塊,分MVC三層進行開發。

3. log4j

Spring Boot supports Log4j 2 for logging configuration if it is on the classpath. If you use the starters for assembling dependencies, you have to exclude Logback and then include log4j 2 instead. If you do not use the starters, you need to provide (at least) spring-jcl in addition to Log4j 2.The simplest path is probably through the starters, even though it requires some jiggling with excludes. The following example shows how to set up the starters in Maven:

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter</artifactId>
	<exclusions>
		<exclusion>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-logging</artifactId>
		</exclusion>
	</exclusions>
</dependency>
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

4. maven-plug: mybatis-generator

修改pom.xml

<!-- <plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
&lt;!&ndash;配置文件的位置&ndash;&gt; <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>false</overwrite>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
</plugin>-->

2.generator-mysql.xml  && mysql-connector-5.1.8.jar

獲取mysql-connector-5.1.8.jar 百度雲鏈接:https://pan.baidu.com/s/1-4FKRmT_URywvp5JvcVEMA

----------------------generator-mysql.xml------------------

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
        "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
    <!-- classPathEntry:數據庫的JDBC驅動,換成你自己的驅動位置 -->
    <classPathEntry location="src/mysql-connector-5.1.8.jar"/>
    <context id="ptf-bas" targetRuntime="MyBatis3">


        <!-- 去除自動生成的註釋 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/doc?useUnicode\=true&amp;characterEncoding\=UTF-8"
                        userId="zl"
                        password="root"></jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>


        <!-- targetProject:自動生成代碼的位置 -->
        <javaModelGenerator targetPackage="com.tianlai.doc.entity"
                            targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
            <property name="trimStrings" value="true"/>
            <property name="constructorBased" value="true"/>


        </javaModelGenerator>
        <sqlMapGenerator targetPackage="mapping"
                         targetProject="src/main/resources">
            <property name="enableSubPackages" value="true"/>
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER"
                             targetPackage="com.tianlai.doc.dao"
                             targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        </javaClientGenerator>
        <!--
        <table tableName="admin" domainObjectName="Admin" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="userId" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="productinf" domainObjectName="Productinf" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="productID" sqlStatement="MySql" identity="true"/>
        </table>
        <table tableName="cusorder" domainObjectName="Cusorder" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
            <generatedKey column="cusId" sqlStatement="MySql" identity="true"/>
        </table>
        -->
        <table tableName="tb_doc_user" domainObjectName="User" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false"
               selectByExampleQueryId="false">
            <generatedKey column="ID" sqlStatement="MySql" identity="true"/>
        </table>
    </context>


</generatorConfiguration>

----------------------generator-mysql.xml------------------


5.thymeleaf


同比JSP,建議讀一讀官網。

----------------------------項目部署---

1.jar包部署

2.war包部署




僅作圖文片段分享經驗,詳情請移步官網:

----------springboot----------

Working with Spring Boot

Ready to actually start using Spring Boot? We have you covered:

 Learning about Spring Boot Features

Need more details about Spring Boot’s core features? The following content is for you:


----------mybatis----------


----------thymeleaf----------




寄語:建議耐心讀官網,你會豁然開朗。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章