本文共 2220 字,大约阅读时间需要 7 分钟。
Spring Boot 是 Spring 应用的一个简化版本,专为快速开发 Java 应用而设计。它整合了 Spring 技栈,提供了一站式解决方案,适合 J2EE 开发。无需手动配置 XML 文件,通过自动配置(@EnableAutoConfiguration)即可快速搭建 Web 应用。
在项目的 pom.xml 中添加如下内容:
org.springframework.boot spring-boot-starter-parent 2.2.1.RELEASE
直接引入需要的场景启动器,例如:
org.springframework.boot spring-boot-starter-web
在主类中使用 @SpringBootApplication 注解:
@SpringBootApplicationpublic class SpringbootApplication { public static void main(String[] args) { SpringApplication.run(SpringbootApplication.class, args); }} YAML 配置文件支持键值对、对象、数组等结构,格式简单易读。例如:
server: port: 8081 path: /hello
引入配置文件处理器:
org.springframework.boot spring-boot-configuration-processor true
Spring Boot 默认使用 SLF4j + Logback 实现日志记录,支持多种日志框架切换。配置文件如下:
logging: file: /var/log/springboot.log pattern: console: '%d{yyyy-MM-dd} [%thread] %-5level %logger{50} - %msg%n' 支持多种方式加载静态资源,例如 jQuery:
org.webjars jquery 3.3.1
推荐使用 Thymeleaf,配置如下:
org.springframework.boot spring-boot-starter-thymeleaf
在模板引擎文件夹下新增 error/404.html,如下:
404页面 404错误页面
在异常处理类中使用 @ResponseBody:
@ResponseBodypublic String handleException(Exception e, HttpServletRequest request) { request.setAttribute("javax.servlet.error.status_code", 500); Map map = new HashMap<>(); map.put("code", "user.notexist"); map.put("message", e.getMessage()); return "forward:/error";} yum install dockersystemctl start dockersystemctl enable docker
# 拉取镜像docker pull tomcat:latest# 运行容器docker run -d -p 8080:8080 tomcat# 停止容器docker stop container-id# 查看容器日志docker logs container-id
新建一个 Maven 项目,添加 Spring Boot Starter 依赖,编写自定义逻辑。
官方命名:spring-boot-starter-[模块]
自定义命名:[模块]-spring-boot-starter
以上内容涵盖了 Spring Boot 的核心知识点,涵盖从入门到高级配置的内容,适合初学的开发者快速上手 Spring Boot 开发。
转载地址:http://ueauz.baihongyu.com/