Spring Boot基础
理念:习惯优于配置,内置习惯性配置,无需手动进行配置。使用Spring boot可以很快创建一个独立运行、准生产级别的基于Spring框架的项目,不需要或者只需很少的Spring配置。
特点
- 内置servlet容器,不需要在服务器部署 tomcat。只需要将项目打成 jar 包,使用 java -jar xxx.jar一键式启动项目;
- SpringBoot提供了starter,把常用库聚合在一起,简化复杂的环境配置,快速搭建spring应用环境。
Spring Boot核心
基本配置
Spring Boot通常有个Application入口类:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
@SpringBootApplication是Spring Boot的核心注解,它是组合注解,源码如下:
@Target({
ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(
excludeFilters = {
@Filter(
type = FilterType.CUSTOM,
classes = {
TypeExcludeFilter.class}
), @Filter(
type = FilterType.CUSTOM,
classes = {
AutoConfigurationExcludeFilter.class}
)}
)
public @interface SpringBootApplication {
}
@SpringBootApplication注解组合了@Configuration、@EnableAutoConfiguration和@ComponentScan注解,若不使用@SpringBootApplication注解,则可以在入口类上直接使用@Configuration、@EnableAutoConfiguration和@ComponentScan。
@EnableAutoConfiguration作用是让Spring Boot根据类路径中的jar包依赖为当前项目进行自动配置。例如,添加了spring-boot-starter-web依赖,会自动添加Tomcat和Spring MVC依赖,那么Spring Boot会对Tomcat和Spring MVC进行自动配置。
@Configuration标注在类上,相当于把该类作为spring的xml配置文件中的<beans>
,作用是配置spring容器。
关闭特定的自动配置
使用@SpringBootApplication的exclude参数关闭特定的自动配置。
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class})
Spring Boot的配置文件
Spring Boot使用一个全局的配置文件application.properties或application.yml。这个全局配置文件可以对一些默认配置的配置值进行修改。如修改Tomcat默认的端口号,并将默认的访问路径"/“修改为”/hello":
server.port=9090
server.context-path=/hello
starter pom
Spring Boot为我们提供了简化企业级开发绝大多数场景的starter pom,只要使用了应用场景所需要的starter pom,相应的配置就可以消除,就可以得到Spring Boot为我们提供的自动配置的bean。
xml配置
Spring Boot提倡零配置,但实际项目中可能需要使用xml配置,此时可以通过Spring提供的@ImportResource来加载xml配置。
@ImportResource({
"classpath:xxx-context.xml", "classpath:yyy-context.xml"})
外部配置
命令行参数配置
Spring Boot是基于jar包运行的,打成jar包的程序可以直接通过下面的命令运行:
java -jar xx.jar
可以通过以下命令修改端口号:
java -jar xx.jar --server.port=9090
常规属性配置
在Spring Boot里,我们只需在application.properties定义属性,直接使用@Value注入即可。
application.properties增加属性:
book.author=tyson
book.name=life
修改入口类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class SpringbootDemoApplication {
@Value("${book.author}")
private String bookAuthor;
@Value("${book.name}")
private String bookName;
@RequestMapping("/")
public String index() {
return "book name: " + bookName + ", written by: " + bookAuthor;
}
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
@RestController=@Controller + @ResponseBody,注解的类里面的方法以json格式输出。
类型安全的配置
Spring Boot提供了基于类型安全的配置方式,通过@ConfigurationProperties将配置文件application.properties中配置的属性值映射到当前类的属性中,从而实现类型安全的配置。
类型安全的bean:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@ConfigurationProperties(prefix = "book")
public class BookConfig {
private String name;
private String author;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
}
通过@ConfigurationProperties加载properties文件内的配置,通过prefix属性指定前缀。
检验代码:
import com.tyson.springbootdemo.config.BookConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
@EnableConfigurationProperties({
BookConfig.class})
public class SpringbootDemoApplication {
@Autowired
public BookConfig bookConfig;
@RequestMapping("/")
public String index() {
return "book name: " + bookConfig.getName() + ", written by: " + bookConfig.getAuthor();
}
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
@EnableConfigurationProperties注解将带有@ConfigurationProperties注解的类注入为Spring容器的Bean。
日志配置
Spring Boot 支持 Log4J、Logback、Java Util Logging、Log4J2 作为日志框架,无论使用哪种日志框架,Spring Boot 已为当前使用日志框架的控制台输出及文件输出做好了配置。默认情况下,Spring Boot 使用 Logback 作为日志框架,日志级别为 INFO。
配置日志文件:
logging.path=H:/log/
logging.file=springbootdemo.log
配置日志级别,格式为 logging.level.包名=级别:
logging.level.root=INFO #root级别,项目所有日志
logging.level.org.springframework.web=DEBUG #package级别
配置日志样式:
logging.pattern.console=%d{yyyy/MM/dd-HH:mm:ss} [%thread] %-5level %logger- %msg%n
logging.pattern.file=%d{yyyy/MM/dd-HH:mm} [%thread] %-5level %logger- %msg%n
Profile配置
Profile 是 Spring 用来针对不同环境对不同配置提供支持的,全局Profile配置使用 application-{profile}.properties(如application-prod.properties)。通过在 application.properties 中设置spring.profiles.active=prod 来制定活动的Profile。
假如有生产和开发环境,生产环境下端口号为80,开发环境下端口号为8888。配置文件如下:
application-prod.properties:
server.port=80
application-dev.properties
server.port=8888
application.properties 增加:
spring.profiles.active=prod
启动程序结果为:
2019-03-03 09:17:08.003 INFO 17812 --- [ main] c.t.s.SpringbootDemoApplication : The following profiles are active: prod
2019-03-03 09:17:11.007 INFO 17812 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8888 (http)
Spring Boot的Web开发
spring-boot-starter-web 为我们提供了嵌入的 tomcat 和 Spring MVC 的依赖。
Thymeleaf 模板引擎
JSP 在内嵌的 Servlet 容器上运行会存在一些问题(内嵌 Tomcat、Jetty 不支持以 jar 形式运行 JSP,Undertow 不支持 JSP)。Spring Boot 提供了大量的模板引擎,包含 FreeMarker、Groovy、Thymeleaf、Velocity 和 Mustache,Spring Boot 中推荐使用 Thymeleaf 作为模板引擎,因为 Thymeleaf 提供了完美的 Spring MVC 的支持。
Thymeleaf 基础知识
Thymeleaf 是 Java 类库,它是一个 xml/xhtml/html5 的模板引擎,可以作为 MVC 的 Web 应用的 view 层。Thymeleaf 还提供了额外的模块与 Spring MVC 集成,使用 Thymeleaf 完全可以替代 JSP。
- 引入 Thymeleaf
基本的 Thymeleaf 模板页面,引入了 Bootstrap(作为样式控制)和 jQuery(DOM 操作)。
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<link th:src="@{bootstrap/css/bootstrap.min.css}" rel="stylesheet">
<link