Spring boot使用

发布于:2025-05-27 ⋅ 阅读:(57) ⋅ 点赞:(0)

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. 创建项目

  2. 编写 RESTful API

  3. @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("test@example.com");
              User savedUser = userService.save(user);
              assertNotNull(savedUser.getId());
          }
      }

常见问题

  1. 自动配置冲突

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

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

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

 

 

 

 

 

 

 

 


网站公告

今日签到

点亮在社区的每一天
去签到