Spring boot使用

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

核心特性

  1. 自动配置

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

    • 一站式 Maven/Gradle 依赖管理,简化依赖配置。
    • 常用依赖:
    <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. 创建项目

  2. 编写 RESTful API

复制代码
   @RestController
   @RequestMapping("/api")
   public class UserController {
       @Autowired
       private 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/mydb
    username: root
    password: secret
  jpa:
    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 {
      @Override
      protected void configure(HttpSecurity http) throws Exception {
          http
              .authorizeRequests()
              .antMatchers("/public/**").permitAll()
              .anyRequest().authenticated()
              .and()
              .formLogin();
      }
  }

异步处理

  • 使用@Async注解启用异步方法:
复制代码
  @Service
  public class EmailService {
      @Async
      public 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 {
          @Autowired
          private UserService userService;
    
          @Test
          void testCreateUser() {
              User user = new User("[email protected]");
              User savedUser = userService.save(user);
              assertNotNull(savedUser.getId());
          }
      }

常见问题

  1. 自动配置冲突

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

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

    • 合理配置线程池、连接池参数,避免内存泄漏
相关推荐
coding随想3 小时前
Java中间件简介:构建现代软件的“隐形桥梁”
java·中间件
武昌库里写JAVA6 小时前
Vue.js状态管理: 使用Vuex实现状态统一管理的最佳实践
vue.js·spring boot·毕业设计·layui·课程设计
superkcl20226 小时前
【JAVA】【Stream流】
java·windows·python
mldong7 小时前
mldong 快速开发框架登录模块设计与实现
java·后端·架构
远方16097 小时前
53-Oracle sqlhc多版本实操含(23 ai)
大数据·数据库·sql·oracle·database
bulucc7 小时前
Maven 或 Gradle 下载和添加 jar 文件的步骤
java·maven·jar
我爱Jack7 小时前
@annotation:Spring AOP 的“精准定位器“
java·后端·spring
ZHOU_WUYI7 小时前
Python Minio库连接和操作Minio数据库
数据库·ragflow
安 当 加 密7 小时前
如何通过密钥管理系统实现数据库、操作系统账号和密码的安全管理
网络·数据库·安全
一ge科研小菜鸡8 小时前
编程语言的演化与选择:技术浪潮中的理性决策
java·c语言·python