Spring boot使用

06-01 1234阅读

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

核心特性

  1. 自动配置

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

      • 一站式 Maven/Gradle 依赖管理,简化依赖配置。
      • 常用依赖:

    org.springframework.boot
    spring-boot-starter-web


    org.springframework.boot
    spring-boot-starter-data-jpa

嵌入式服务器

  • 内置 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生成基础项目结构,选择所需依赖。
        • 编写 RESTful API

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

          配置文件

        • 使用application.properties或application.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 {
              Optional 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 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 处理日志。
            • 使用分层架构

              Spring boot使用
              (图片来源网络,侵删)
              • 控制器层(Controller)→ 服务层(Service)→ 数据访问层(Repository)。
              • 配置外部化

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

                  Spring boot使用
                  (图片来源网络,侵删)
                  • 使用@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 = ...)排除特定自动配置类。
                      • 依赖版本管理

                        Spring boot使用
                        (图片来源网络,侵删)
                        • Spring Boot 通过spring-boot-dependencies统一管理依赖版本,避免冲突。
                        • 性能优化

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

                     

                     

                     

                     

                     

                     

                     

                     

免责声明:我们致力于保护作者版权,注重分享,被刊用文章因无法核实真实出处,未能及时与作者取得联系,或有版权异议的,请联系管理员,我们会立即处理! 部分文章是来自自研大数据AI进行生成,内容摘自(百度百科,百度知道,头条百科,中国民法典,刑法,牛津词典,新华词典,汉语词典,国家院校,科普平台)等数据,内容仅供学习参考,不准确地方联系删除处理! 图片声明:本站部分配图来自人工智能系统AI生成,觅知网授权图片,PxHere摄影无版权图库和百度,360,搜狗等多加搜索引擎自动关键词搜索配图,如有侵权的图片,请第一时间联系我们。

目录[+]

取消
微信二维码
微信二维码
支付宝二维码