php 网站,软件工程公司,WordPress适合建大型网站吗,张北网站seoSpring Boot 是一个基于 Spring 框架的扩展#xff0c;旨在简化新 Spring 应用的初始搭建以及开发过程。它通过自动配置和约定优于配置的原则#xff0c;减少了开发者的工作量。Spring Boot 提供了一组核心注解和 Starter 依赖管理工具来帮助开发者快速启动项目。
1. Spring…Spring Boot 是一个基于 Spring 框架的扩展旨在简化新 Spring 应用的初始搭建以及开发过程。它通过自动配置和约定优于配置的原则减少了开发者的工作量。Spring Boot 提供了一组核心注解和 Starter 依赖管理工具来帮助开发者快速启动项目。
1. SpringBootApplication
这是 Spring Boot 应用程序的核心注解通常放置在主类上。它实际上是一个组合注解包含了三个主要注解的功能
Configuration标记该类为配置类可以定义bean。EnableAutoConfiguration启用自动配置根据类路径中的依赖库自动配置Spring应用。ComponentScan启动组件扫描自动发现并注册带有特定注解如Component, Service, Repository的bean。
SpringBootApplication
public class MyApplication {public static void main(String[] args) {SpringApplication.run(MyApplication.class, args);}
}
2. RestController 和 Controller
RestController用于创建RESTful Web服务控制器方法返回的数据会直接被转换成HTTP响应体。Controller传统MVC模式下的控制器通常配合视图解析器使用方法返回的是逻辑视图名或模型数据。
RestController
RequestMapping(/api)
public class MyRestController {GetMapping(/hello)public String hello() {return Hello World!;}
}
3. Autowired
用于自动注入依赖。它可以作用于构造函数、字段或者setter方法推荐使用构造函数注入以保证不可变性和强制性依赖。
Service
public class MyService {private final MyRepository myRepository;Autowired // 可选构造函数注入默认启用Autowiredpublic MyService(MyRepository myRepository) {this.myRepository myRepository;}
}
4. Service, Repository, Component
这些注解用于标注不同层次的组件
Service业务逻辑层。Repository数据访问层即DAO组件。Component通用组件当组件不属于上述任何一层时使用。
Repository
public class MyRepository {// ...
}
5. Entity
用于标识JPA持久化实体类与数据库表对应。
Entity
public class User {IdGeneratedValue(strategy GenerationType.IDENTITY)private Long id;private String name;// getters and setters
}
6. RequestMapping, GetMapping, PostMapping, 等
用于映射HTTP请求到具体的方法上。RequestMapping 是通用的而其他注解如 GetMapping、PostMapping、PutMapping、DeleteMapping 分别对应HTTP方法GET、POST、PUT、DELETE。
GetMapping(/users/{id})
public ResponseEntityUser getUserById(PathVariable Long id) {// ...
}
7. Configuration 和 Bean
Configuration标识配置类可以包含多个Bean方法。Bean用于声明一个bean相当于XML配置中的bean标签。
Configuration
public class AppConfig {Beanpublic MyService myService() {return new MyServiceImpl();}
}
8. Scheduled
用于定时任务的方法可以指定固定延迟、固定速率等参数。
Component
public class ScheduledTasks {Scheduled(fixedRate 5000)public void reportCurrentTime() {System.out.println(The time is now Calendar.getInstance().getTime());}
}
这些注解大大简化了Spring应用程序的开发过程使得开发者可以专注于业务逻辑而不是复杂的框架配置。