参考:spring-Boot-renference-guide-zh.pdf
1 添加依赖
使用maven构建web工程,添加以下依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
</parent>
<dependencies>
<!--web应用依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2 使用@SpringBootApplication注解
@SpringBootApplication 注解默认使用@Configuration,@EnableAutoConfigutation和@ComponentScan
@Configuration定义配置类,可替换xml配置文件
@EnableAutoConfigutation ,使用这个注解之后,就不需要使用@Import注解导入配置文件
@ComponentScan 注解扫描beans
关于Configuration和@ComponentScan注解的使用可以看spring纯注解开发
@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 {
……
3 入门Demo
demo目录
springboot应用启用类DemoApplication
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args){
SpringApplication.run(DemoApplication.class,args);
}
}
TestController
@RestController
public class TestController {
@GetMapping("hello")
public String helloWord(){
//返回json数据
return "hello World!";
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>index</title>
</head>
<body>
<a href="/hello">spring boot入门</a>
</body>
</html>
启动DemoApplication,访问http://localhost:8080/hello 可以看到输出字符串
4 热部署
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
<scope>true</scope>
</dependency>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
参考: https://blog.csdn.net/qq_37598011/article/details/80778915
devtools可以实现页面热部署(即页面修改后会立即生效,这个可以直接在application.properties文件中配置spring.thymeleaf.cache=false来实现)
即devtools会监听classpath下的文件变动,并且会立即重启应用(发生在保存时机),
注意:因为其采用的虚拟机机制,该项重启是很快的
(1)base classloader (Base类加载器):加载不改变的Class,例如:第三方提供的jar包。
(2)restart classloader(Restart类加载器):加载正在开发的Class。 -->
为什么重启很快,因为重启的时候只是加载了在开发的Class,没有重新加载第三方的jar包。
application.properties
#"关闭缓存, 即时刷新"
#spring.freemarker.cache=false
#spring.thymeleaf.cache=true 如果开启此处会导致每次输入删除都会自动刷新哪怕你没保存
#热部署生效
spring.devtools.restart.enabled=true
#设置重启的目录,添加那个目录的文件需要restart
spring.devtools.restart.additional-paths=src/main/java
spring.devtools.restart.exclude=WEB-INF/**
5 多开发环境配置
SpringApplication将从以下位置加载application.properties文件,并把他们添加到spring Environment中
- 当前目录下的/config子目录
当前目录
classpath下的/config子目录
classpath跟路径root
profile-specific属性能通过命名惯例 application-{profile}.properties 定义。 Environment (Spring的环境抽象接口) 有个默认profiles集合(默认情况为 [default] ) ,在没有设置激活的profiles时会被使用(例如,如果没有明确指定激活的profiles, application-default.properties 中的属性会被加载。
设置多环境配置可以采用
application-dev.properties
spring.datasource.url=jdbc:mysql://localhost:3306/test?&characterEncoding=utf8&useUnicode=true&useSSL=true&autoReconnect=true
spring.datasource.username=test
spring.datasource.password=test
server.port=8087
application-pro.properties
#生产环境配置
spring.datasource.url=jdbc:mysql://localhost:3306/study?&characterEncoding=utf8&useUnicode=true&useSSL=true&autoReconnect=true
ckeditor.access.image.url=https://cett.csdc.info/images/
spring.datasource.username=root
spring.datasource.password=root
server.port=8080
application.properties
spring.profiles.active=dev
springboot 会加载使用 application.properties 和 application-dev.properties 配置文件的信息
6 日志
6.1 Logback
采用内置的logback时配置文件logback-spring.xml或logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<include resource="org/springframework/boot/logging/logback/base.xml"/>
<!-- 文件输出格式 -->
<!-- %d日期,%p日志级别,%t线程名,%c类的全名,% %logger:显示logger名 %L输出触发日志事件的行号,%msg:日志消息,%n是换行符-->
<property name="PATTERN" value="%d{yyyy-MM-dd HH:mm:ss.SSS} |%p [%t] %c %logger{36} -| %msg%n" />
<!-- 开发环境 -->
<!-- 当加载application-dev.proerties时加载此配置 -->
<springProfile name="dev">
<!-- appender是configuration的子节点,是负责写日志的组件。 -->
<!-- ConsoleAppender:把日志输出到控制台 -->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${PATTERN}</pattern>
</encoder>
</appender>
<!-- 指定项目中某个包,当有日志操作行为时的日志记录级别
cc.study.springBootDemo为根包,也就是只要是发生在这个根包下面的所有日志操作行为的权限都是DEBUG
级别依次为【从高到低】:FATAL > ERROR > WARN > INFO > DEBUG > TRACE -->
<logger name="cc.study.springBootDemo" level="debug" />
<root level="info">
<appender-ref ref="CONSOLE" />
</root>
</springProfile>
<!-- 测试环境 -->
<springProfile name="test">
<!-- 每天产生一个文件 -->
<!-- 以下的大概意思是:1.先按日期存日志,日期变了,将前一天的日志文件名重命名为XXX%日期%索引,新的日志仍然是demo.log -->
<!-- 2.如果日期没有发生变化,但是当前日志的文件大小超过1KB时,对当前日志进行分割 重命名-->
<appender name="TEST-FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!-- 文件路径 -->
<file>./logs/app.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!-- 文件名称 -->
<!-- 活动文件的名字会根据fileNamePattern的值,每隔一段时间改变一次 -->
<!-- 文件名:logs/demo.2017-12-05.0.log -->
<fileNamePattern>./logs/demo.%d{yyyy-MM-dd}.log</fileNamePattern>
<!-- 文件最大保存历史数量 -->
<MaxHistory>100</MaxHistory>
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<!-- maxFileSize:这是活动文件的大小,默认值是10MB,测试时可改成1KB看效果 -->
<maxFileSize>1KB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
<encoder>
<Pattern>${PATTERN}</Pattern>
<charset>UTF-8</charset>
</encoder>
</appender>
</springProfile>
<!-- 生产环境 -->
<springProfile name="prod">
<appender name="PROD_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>./logs/app.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>./logs/demo.%d{yyyy-MM-dd}.log</fileNamePattern>
<MaxHistory>100</MaxHistory>
</rollingPolicy>
<layout class="ch.qos.logback.classic.PatternLayout">
<pattern>${PATTERN}</pattern>
</layout>
</appender>
<root level="warn">
<appender-ref ref="PROD_FILE" />
</root>
</springProfile>
</configuration>
生成的日志文件
6.2 sl4j
因为springBoot内置了sl4j的依赖,就算我们不在pom文件中添加依赖,springboot也会自动引入sl4j的jar包
@RestController
public class TestController {
Logger logger = LoggerFactory.getLogger(TestController.class);
@GetMapping("hello")
public String helloWord(HttpServletRequest request){
logger.info("ip为:{},访问:{}",request.getRemoteAddr(),request.getRequestURI());
return "hello World!";
}
}