当前位置: 首页 > ai >正文

Spring boot使用

Spring Boot 是基于 Spring 框架的开发工具,旨在简化 Spring 应用的初始搭建和开发过程。它通过自动配置约定优于配置的理念,让开发者可以快速上手,专注于业务逻辑而非框架配置。

核心特性

  1. 自动配置

    • 根据项目依赖自动配置 Spring 框架,减少 XML 和 Java 配置。
    • 例如:引入spring-boot-starter-web会自动配置嵌入式 Tomcat 服务器和 Spring MVC。
  2. 起步依赖(Starters)

    • 一站式 Maven/Gradle 依赖管理,简化依赖配置。
    • 常用依赖:
<!-- Maven示例 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

嵌入式服务器

  • 内置 Tomcat、Jetty 或 Undertow,无需部署 WAR 文件。
  • 通过@SpringBootApplication注解启动应用:
@SpringBootApplication
public class MyApp {public static void main(String[] args) {SpringApplication.run(MyApp.class, args);}
}

Actuator

  • 提供生产级监控和管理端点(如健康检查、指标收集、环境信息)。
  • 配置:
  • management:endpoints:web:exposure:include: "*"  # 暴露所有端点

快速上手

  1. 创建项目

    • 使用Spring Initializr生成基础项目结构,选择所需依赖。
  2. 编写 RESTful API

  3. @RestController
    @RequestMapping("/api")
    public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users/{id}")public ResponseEntity<User> getUser(@PathVariable Long id) {return ResponseEntity.ok(userService.findById(id));}@PostMapping("/users")public ResponseEntity<User> createUser(@RequestBody User user) {return ResponseEntity.created(URI.create("/api/users/" + userService.save(user).getId())).build();}
    }
    

    配置文件

  4. 使用application.propertiesapplication.yml配置应用:
server:port: 8081  # 修改默认端口
spring:datasource:url: jdbc:mysql://localhost:3306/mydbusername: rootpassword: secretjpa:hibernate:ddl-auto: update  # 自动更新数据库表结构

集成与扩展

  1. 数据库访问

    • 使用 Spring Data JPA 简化数据库操作:
    • public interface UserRepository extends JpaRepository<User, Long> {Optional<User> findByEmail(String email);
      }

安全认证

  • 集成 Spring Security:
  • @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {@Overrideprotected void configure(HttpSecurity http) throws Exception {http.authorizeRequests().antMatchers("/public/**").permitAll().anyRequest().authenticated().and().formLogin();}
    }

异步处理

  • 使用@Async注解启用异步方法:
  • @Service
    public class EmailService {@Asyncpublic CompletableFuture<Void> sendEmail(String to) {// 异步发送邮件return CompletableFuture.completedFuture(null);}
    }

部署与监控

  1. 打包与运行

    • 打包为可执行 JAR:
    • mvn clean package
      java -jar target/myapp-0.0.1-SNAPSHOT.jar

Docker 化

  • 创建 Dockerfile:
  • FROM openjdk:17-jdk-slim
    COPY target/myapp.jar app.jar
    ENTRYPOINT ["java","-jar","/app.jar"]
    

  • 监控与日志

    • 结合 Prometheus 和 Grafana 收集指标,使用 ELK Stack 处理日志。
  • 使用分层架构

    • 控制器层(Controller)→ 服务层(Service)→ 数据访问层(Repository)。
  • 配置外部化

    • 使用环境变量、配置中心(如 Spring Cloud Config)管理不同环境的配置。
  • 单元测试

    • 使用@SpringBootTest@WebMvcTest编写测试:
    • @SpringBootTest
      class UserServiceTest {@Autowiredprivate UserService userService;@Testvoid testCreateUser() {User user = new User("test@example.com");User savedUser = userService.save(user);assertNotNull(savedUser.getId());}
      }

常见问题

  1. 自动配置冲突

    • 使用@SpringBootApplication(exclude = ...)排除特定自动配置类。
  2. 依赖版本管理

    • Spring Boot 通过spring-boot-dependencies统一管理依赖版本,避免冲突。
  3. 性能优化

    • 合理配置线程池、连接池参数,避免内存泄漏

 

 

 

 

 

 

 

 

http://www.xdnf.cn/news/8550.html

相关文章:

  • Git使用
  • 串扰与反射对信号完整性的影响
  • Spring Boot微服务架构(四):微服务的划分原则
  • 精益数据分析(82/126):先行指标驱动的增长黑客策略——从相关性到因果性的跨越
  • 基于大模型预测的视神经脊髓炎技术方案
  • Java—— IO流的应用
  • Python 爬虫之requests 模块的应用
  • Trae(The Real Al Engineer)
  • SQL每日一练(2)
  • Vue3响应式数据: 深入分析Ref与Reactive
  • React 文件分片上传与下载全解析
  • 听课笔记之中国式现代化导论
  • 提效-点击跳转到源码
  • C++系统IO
  • 电脑C盘清理技巧:释放空间,提升性能
  • 【MySQL】表的内外连接
  • 缓存的更新机制
  • 计算机网络期末复习资料
  • 建筑机械员(建筑施工机械管理人员)考试练习题
  • Gartner《Optimize GenAI Strategy for 4 Key ConsumerMindsets》学习心得
  • Netty学习专栏(四):如何解决粘包/拆包问题及自定义协议的实现
  • 网络安全从零开始(一):基础技能全解析
  • github好玩的工具
  • 车载中央域控制器测试【BCM模块介绍-外灯3】
  • SQL每日一题
  • 【MySQL】CRUD
  • SQL每日一题(4)
  • ae钢笔工具无法编辑形状图层的路径
  • Laravle 证件照排版
  • 预分配矩阵内存提升文件数据读取速度