springboot
应用 springboot
应用没有相应的archetype
,不能通过mvn generate:archetype
创建,一般有两种方式创建一个springboot
应用:
https://start.spring.io/
,选择Web
依赖,点击Generate Project
创建一个springboot
应用。File -> New Project -> Spring Initializr -> Choose Initializr Service URL(https://start.spring.io) -> next(填写 Project Metadata) -> next -> 选择Web -> Finish
mvn spring-boot:run
# 或
mvn clean spring-boot:run
@SpringBootApplicatoin
是用的@ComponentScan
扫描,扫描的是Component
,包括@Component
, @Controller
, @Service
, @Repository
等。
SpringBootApplication
默认扫描运行类所在包及其子包中的Component
。
spring-boot-starter-test
Starter 通常通过添加 spring-boot-starter-test
"Starter"依赖来导入 Spring Boot test 模块以及 JUnit, AssertJ, Hamcrest, Spring Test, Mockito, JSONassert and JSONPath 库,如果这些库满足不了你的需要,你可以再添加其他的测试依赖。
<!-- spring-boot-starter-test imports both Spring Boot test modules as well as JUnit, AssertJ, Hamcrest, Spring Test, Mockito, JSONassert and JSONPath -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
A Spring Boot application is a Spring
ApplicationContext
, so nothing very special has to be done to test it beyond what you would normally do with a vanilla Spring context.
Spring Boot provides a
@SpringBootTest
annotation, which can be used as an alternative to the standard spring-test@ContextConfiguration
annotation when you need Spring Boot features. The annotation works by creating theApplicationContext
used in your tests throughSpringApplication
.
pom.xml
中添加MyBatis依赖 <!-- mybatis ORM 框架 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
<!-- MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
<scope>runtime</scope>
</dependency>
<!-- Druid 数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
application.properties
中添加相关配置spring.datasource.url=jdbc:mysql://127.0.0.1:3306/erp?autoReconnect=true&allowMultiQueries=true&zeroDateTimeBehavior=convertToNull
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
# \u521D\u59CB\u5316\u5927\u5C0F\uFF0C\u6700\u5C0F\uFF0C\u6700\u5927
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
# \u914D\u7F6E\u83B7\u53D6\u8FDE\u63A5\u7B49\u5F85\u8D85\u65F6\u7684\u65F6\u95F4
spring.datasource.maxWait=60000
# mybatis
mybatis.mapper-locations=classpath*:mapping/*.xml
mybatis.type-aliases-package=net.mrliuli.erp.domain.entity
pom.xml
中添加插件 <!-- Mybatis Generator 插件 =================================================== -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.5</version>
<dependencies>
<!-- 数据库驱动 -->
<!-- 如果不在此声明这个依赖,可以在 mybatis-generator.xml中通过<classPathEntry><classPathEntry>添加 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
</dependencies>
<configuration>
<!-- 允许移动生成的文件 -->
<verbose>true</verbose>
<!-- 是否覆盖 -->
<overwrite>true</overwrite>
<!-- 自动生成的配置 -->
<configurationFile>
src/main/resources/mybatis-generator.xml
</configurationFile>
</configuration>
</plugin>
<!-- =================================================== Mybatis Generator 插件 -->
src/main/resources/mybatis-generator.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>
<context id="erp" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接地址账号密码-->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://127.0.0.1:3306/erp"
userId="root"
password="123456">
</jdbcConnection>
<!-- 默认false:把JDBC DECIMAL 和 NUMERIC 类型解析为 Integer; true:把JDBC DECIMAL 和 NUMERIC 类型解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成Entity实体类存放位置 -->
<javaModelGenerator targetPackage="net.mrliuli.erp.domain.entity" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!--生成映射文件存放位置-->
<sqlMapGenerator targetPackage="net.mrliuli.erp.mapping" targetProject="src/main/resources">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!--生成Dao类(接口)存放位置-->
<!-- 客户端代码,生成易于使用的针对Entity对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<javaClientGenerator type="XMLMAPPER" targetPackage="net.mrliuli.erp.mapper" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!--生成对应表及类名-->
<table tableName="t_sales_order" domainObjectName="SalesOrder"
enableCountByExample="false" enableUpdateByExample="false"
enableDeleteByExample="false" enableSelectByExample="false"
selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
# mybatis
# mapper-locations 的目录结构要用斜杠形式,不能用点!
mybatis.mapper-locations=classpath*:net/mrliuli/erp/mapping/*.xml
mybatis.type-aliases-package=net.mrliuli.erp.domain.entity
mvn mybatis-generator:generate
spring-boot-devtools
实现热部署方便调试 spring-boot-devtools
用于实现热交换,开发者添加该依赖后,当类路径下的类有更改时,不需要手动重启,即可实现类的更新替换。
pom.xml
中添加依赖: <!-- 开发人员工具 -->
<!-- 运行打包的应用程序时,开发人员工具会自动禁用。如果你通过 java -jar或者其他特殊的类加载器进行启动时,都会被认为是“生产环境的应用”。 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<!-- optional=true,依赖不会传递,该项目依赖devtools;之后依赖该项目的项目如果想要使用devtools,需要重新引入 -->
<optional>true</optional>
</dependency>
IntellJ IDEA
以使其触发spring-boot-devtools
“File” -> “Settings” -> “Build,Execution,Deplyment” -> “Compiler”,选中打勾 “Build project automatically” 。
F12,打开开发者工具,“Network” 选项卡下 选中打勾 “Disable Cache(while DevTools is open)”
对于spring-boot web
应用,因其内嵌有servlet
容器,所以有两种打包方式:一是打成jar包,直接执行,另一种就是传统方式,打成war包放到tomcat下执行。
# cd到项目根目录
mvn clean package
# 直接执行
java -jar target/spring-boot-scheduler-1.0.0.jar
打成可部署的war包(即传统方式,注意不支持WebFlux
应用),使用非内嵌tomcat
。
Step 1
:提供一个SpringBootServletInitializer
的子类并重写configure
方法。Spring Framework’s Servlet 3.0
支持,当servlet
容器启动的时候,来配置你的应用。通常是将Application
类继承SpringBootServletInitializer
,如下:@SpringBootApplication
public class Application extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
Step 2
:修改pom.xml
打包方式为war
<packaging>war</packaging>
Step 3
:解决内嵌的servlet
容器与部署war
的servlet
容器之间的冲突。只需将内嵌的servlet
容器的依赖scope
标记为provided
,如下(该项目是tomcat):<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
Step 4
:打包运行:# cd到项目根目录
mvn clean package
# 复制`target/erp-0.0.1-SNAPSHOT.war`到`%TOMCAT_HOME%/webapps/`下,启动tomcat执行。
浏览器输入 `http://localhost:8080/erp-0.0.1-SNAPSHOT/` 测试
Spring Boot
也是通过profile
来实现多环境配置的。
application-{profile}.properties
文件 多环境配置文件名需要满足格式application-{profile}.properties
,注意application
与{profile}
之间是短杠。
PC@P0005 MINGW64 /d/program/sa/erp/src/main/resources (master)
$ ll
total 12
-rw-r--r-- 1 PC 197121 675 五月 3 10:10 application.properties
-rw-r--r-- 1 PC 197121 274 五月 3 10:00 application-dev.properties
-rw-r--r-- 1 PC 197121 274 五月 3 10:01 application-release.properties
-rw-r--r-- 1 PC 197121 272 五月 3 10:01 application-test.properties
-rw-r--r-- 1 PC 197121 274 五月 3 10:01 application-uat.properties
spring.profiles.active
属性 在application.properties
文件中修改spring.profiles.active
属性的值,如:
# PROFILES
# Comma-separated list of active profiles. Can be overridden by a command line switch.
spring.profiles.active=dev
启动时设置8081
端口,设置使用application-dev.properties
配置文件。
java -jar target/spring-boot-scheduler-1.0.0.jar --port=8081 --spring.profiles.active=dev
json
接口开发 传统的Spring
开发中,要返回json
格式,需要添加jackson
等相关jar包,配置spring controller
扫描,以及在对应的方法上添加@ResponseBody
。
对于Spring Boot
,只需要类添加@RestController
,则默认类中的方法都会以json
的格式返回。
只要返回的类型能被Jackson2
序列化(对于POJO或Groovy对象总是可以序列化)。Note that, in a browser, you might sometimes see XML responses, because browsers tend to send accept headers that prefer XML.
HTML
页面与Thymeleaf
模板引擎 SpringBoot应用是没有webapp
目录的。
Do not use the
src/main/webapp
directory if your application is packaged as a jar. Although this directory is a common standard, it works only with war packaging, and it is silently ignored by most build tools if you generate a jar.
Spring Boot
从类路径或ServletContext
根路径的如下目录中加载静态内容:/static
/public
/resources
/META-INF/resources
Spring Boot
使用Spring MVC
的ResourceHttpRequestHandler
来处理静态内容。/**
,可以通过如下属性改变映射,如:spring.mvc.static-path-pattern=/resources/**
Spring Boot supports both static and templated welcome pages. It first looks for an
index.html
file in the configured static content locations. If one is not found, it then looks for anindex
template. If either is found, it is automatically used as the welcome page of the application.
以上是官网的介绍,但经过测试,实际并不是如上所述,测试的结果是:
"/"
的RequestMapping
所映射的模板面面。index.html
。Spring Boot looks for a
favicon.ico
in the configured static content locations and the root of the classpath (in that order). If such a file is present, it is automatically used as the favicon of the application.
Themeleaf
模板引擎) Spring Boot建议不使用JSP
,建议使用Themeleaf
来做动态页面。
Themeleaf
依赖。<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Themeleaf
模板引擎时,默认配置自动从src/main/resources/templates
路径加载模板文件。/**
* 需要返回页面,则不能使用`@RestController`(会将返回值转换成`JSON`)!
*/
@Controller
public class HomeController {
@RequestMapping("/")
public String index(HttpServletRequest request){
request.setAttribute("key", "welcome, this is a dynamic page!");
/**
* Spring Boot 使用`Thymeleaf`模板引擎默认从`src/main/resources/templates`加载动态页面,
* 所以,这里将跳转到`templates/index.html`动态页面。
*/
return "index";
}
}
SLF4J——Simple Logging Facade For Java,它是一个针对于各类Java日志框架的统一Facade抽象。Java日志框架众多——常用的有java.util.logging, log4j, logback,commons-logging, Spring框架使用的是Jakarta Commons Logging API (JCL)。而SLF4J定义了统一的日志抽象接口,而真正的日志实现则是在运行时决定的——它提供了各类日志框架的binding。
Spring Boot在所有内部日志中使用Commons Logging
,即Spring Boot框架使用的是Commons Logging
。
默认情况下,Spring Boot应用使用Logback
记录日志,并用INFO
级别输出到控制台。
2014-03-05 10:57:51.112 INFO 45469 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/7.0.52
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2014-03-05 10:57:51.253 INFO 45469 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1358 ms
2014-03-05 10:57:51.698 INFO 45469 --- [ost-startStop-1] o.s.b.c.e.ServletRegistrationBean : Mapping servlet: 'dispatcherServlet' to [/]
2014-03-05 10:57:51.702 INFO 45469 --- [ost-startStop-1] o.s.b.c.embedded.FilterRegistrationBean : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
具体元素如下:
ERROR
, WARN
, INFO
, DEBUG
or TRACE
---
标识实际日志的开始Logback does not have a FATAL level. It is mapped to ERROR.
日志级别从低到高分为TRACE
< DEBUG
< INFO
< WARN
< ERROR
< FATAL
,Spring Boot中默认配置ERROR
、WARN
和INFO
级别的日志输出到控制台。
配置DEBUG
输出级别,两种方式:
application.properties
中配置 debug=true
。该属性置为true
的时候,核心Logger(包含嵌入式容器、hibernate、spring)会输出更多内容,但是自己应用的日志并不会输出为DEBUG
级别。 另外,也可以通过启用trace
模式来输出TRACE
级别日志,如 starting your application with a --trace
flag (or trace=true
in your application.properties)。
All the supported logging systems can have the logger levels set in the Spring Environment (for example, in application.properties) by using logging.level.= where level is one of TRACE, DEBUG, INFO, WARN, ERROR, FATAL, or OFF. The root logger can be configured by using logging.level.root.
The following example shows potential logging settings in application.properties:
logging.level.root=WARN
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
By default, Spring Boot logs only to the console and does not write log files. If you want to write log files in addition to the console output, you need to set a logging.file or logging.path property (for example, in your application.properties).
logging.file
,设置文件,可以是绝对路径,也可以是相对路径。如:logging.file=my.log
logging.path
,设置目录,会在该目录下创建spring.log
文件,并写入日志内容,如:logging.path=/var/log
如果只配置 logging.file
,会在项目的当前路径下生成一个 xxx.log
日志文件。
如果只配置 logging.path
,在 /var/log
文件夹生成一个日志文件为 spring.log
。
注:二者不能同时使用,如若同时使用,则只有logging.file生效
Since logging is initialized before the ApplicationContext is created, it is not possible to control logging from @PropertySources in Spring @Configuration files. The only way to change the logging system or disable it entirely is via System properties.
根据不同的日志系统,如下规则组织配置文件名,就能被正确加载:
Logging System 日志系统 | Customization 自定义日志配置文件名 |
---|---|
Logback | logback-spring.xml , logback-spring.groovy , logback.xml , or logback.groovy |
When possible, we recommend that you use the -spring variants for your logging configuration (for example, logback-spring.xml rather than logback.xml). If you use standard configuration locations, Spring cannot completely control log initialization.