目录
- 1、 @SpringBootApplication
- 2、@RestController
- 3、@Controller
- 4、@ResponseBody
- 5、@RequestMapping
- 6、@GetMapping
- 7、@RequestParam
- 8、@DateTimeFormat
- 8、@RequestBody
- 9、@PathVariable
- 10、@Component
- 11、@Autowired
- 12、@Qualifier
- 13、@ComponentScan
- 14、@Primary
- 15、@Resource
- 16、@Mapper
- 17、@SpringBootTest
- 18、@RestControllerAdvice
- 19、@ExceptionHandler
- 20、@ConditionalOnMissingBean
- 21、@ConfigurationProperties
- 22、@EnableTransactionManagement
- 23、@JsonFormat
1、 @SpringBootApplication
标注SpringBoot的入口,用于启动SpringBoot应用程序
@SpringBootApplication
public class SpringbootProject01Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootProject01Application.class, args);
}
}
2、@RestController
@RestController是Spring框架中的一个注解,用于创建RESTful Web服务。
它是一个组合注解,相当于同时使用了@Controller和@ResponseBody两个注解。
作用于:业务层
@RestController
public class MyRestController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
3、@Controller
将类标记为Spring MVC的控制器。它负责处理请求,并返回响应。
通常用于处理视图渲染的场景,而不是直接返回数据。
返回值通常是一个视图名称或一个ModelAndView对象,这将告诉Spring MVC渲染相应的视图并返回给客户端。
@Controller
public class MyController {
@RequestMapping("/hello")
public String sayHello(Model model) {
model.addAttribute("message", "Hello, World!");
return "hello"; // 视图名称
}
}
4、@ResponseBody
指明方法的返回值应直接写入HTTP响应体中,而不是解析为跳转路径。用于返回JSON或其他数据格式的响应。
@Controller
public class MyController {
@GetMapping("/hello")
@ResponseBody
public String sayHello() {
return "Hello, World!";
}
}
5、@RequestMapping
处理请求地址映射,作用于类或方法上,可以接收所有类型的请求,例如:GET、POST
@RequestMapping("/hello")
public String hello() {
System.out.println("Hello World!!!");
return "Hello World!!!";
}
6、@GetMapping
处理GET请求地址映射
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
7、@RequestParam
参数映射,将name参数的值映射到username中。
@RequestMapping("/springBootParam")
public String springBootParam(@RequestParam(name = "name") String username, Integer age) {
System.out.println(username + ":" + age);
return "OK";
}
设置默认值
public Result page(@RequestParam(defaultValue = "1") Integer pageNumber, @RequestParam(defaultValue = "3") Integer pageSize) {
...
}
7.1 设置必填与可选参数
required = true【必填】— 默认 — 不传会报错
required = false【可选】— 不传是null
@RequestMapping("/springBootParam")
public String springBootParam(@RequestParam(name = "name", required = true) String username, Integer age) {
System.out.println(username + ":" + age);
return "OK";
}
8、@DateTimeFormat
解析格式化日期时间
@PostMapping("/process")
public String processDate(@DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
// 在这里可以使用解析后的日期对象date
return "success";
}
8、@RequestBody
将JSON格式的数据封装到对象中
@RequestMapping("/jsonParam")
public String jsonParam(@RequestBody User user) {
System.out.println(user);
return "OK";
}
9、@PathVariable
获取路径参数
@RequestMapping("pathParam/{id}")
public String pathParam(@PathVariable Integer id) {
System.out.println(id);
return "OK";
}
@RequestMapping("pathParams/{id}/{name}")
public String pathParams(@PathVariable Integer id, @PathVariable String name) {
System.out.println(id + "-" + name);
return "OK";
}
10、@Component
控制反转:简称IOC。对象创建的控制权由程序自身转移到外部(容器),这种思想称为控制反转。
@Component
public class EmpServiceImplB implements EmpService {}
11、@Autowired
依赖注入:简称DI。容器为应用程序提供运行时所依赖的资源,称之为依赖注入。
@Autowired
private EmpService empService;
12、@Qualifier
用于解决自动装配时歧义性的注解。当你在 Spring 容器中有多个相同类型的 Bean 时,Spring 默认只会注入一个 Bean,但如果有多个相同类型的 Bean,就会产生歧义性,导致 Spring 不知道应该注入哪一个。
为了解决这个问题,你可以使用 @Qualifier 注解来指定注入哪一个 Bean。在注解的值中,你可以指定要注入的 Bean 的名称。
@Service("empServiceImplA")
public class EmployeeServiceImplA implements EmployeeService {
// ...
}
@Service("empServiceImplB")
public class EmployeeServiceImplB implements EmployeeService {
// ...
}
@Autowired
@Qualifier("empServiceImplB")
private EmployeeService employeeService;
13、@ComponentScan
包扫描器。用于自动扫描某个包(或子包)下的类,并将它们作为 Spring 组件注册到 Spring 容器中【ICO控制反转】。
@Configuration
@ComponentScan(basePackages = "com.example.myapp")
public class AppConfig {
// ...
}
在这个例子中,AppConfig 是一个配置类,通过 @ComponentScan 注解指定了要扫描的包名 com.example.myapp。这意味着 Spring 会扫描这个包及其子包下的所有类,并自动注册那些带有 Spring 注解的类为 Spring 组件。
14、@Primary
设置优先级,用于解决自动装配时的歧义性问题。与@Qualifier作用一致
@Primary
@Service("empServiceImplA")
public class EmployeeServiceImplA implements EmployeeService {
// ...
}
@Service("empServiceImplB")
public class EmployeeServiceImplB implements EmployeeService {
// ...
}
@Autowired
private EmployeeService employeeService;
15、@Resource
用于解决自动装配【依赖注入】时的歧义性问题。与@Qualifier、@Primary作用一致。
@Service("empServiceImplA")
public class EmployeeServiceImplA implements EmployeeService {
// ...
}
@Service("empServiceImplB")
public class EmployeeServiceImplB implements EmployeeService {
// ...
}
@Resource(name = "empServiceImplA")
private EmployeeService employeeService;
16、@Mapper
@Mapper 是一个用于将接口生成一个动态代理类的注解。
它的作用是简化数据库操作代码,避免重复编写相同的 SQL 语句和映射逻辑。
当你在一个接口上使用 @Mapper 注解时,Spring 会自动扫描该接口,并为其生成一个动态代理类。这个动态代理类实现了该接口,并提供了对数据库的 CRUD(增删改查)操作。通过这个动态代理类,你可以直接调用接口方法来进行数据库操作,而不需要编写具体的 SQL 语句和映射逻辑。
@Mapper 注解一般用在 Dao 层【mapper】接口上,相当于一个 mapper.xml 文件的作用。它简化了代码,避免了重复编写相同的 SQL 语句和映射逻辑,提高了开发效率和代码复用性。
@Mapper
public interface UserDao {
List<User> selectAll();
User selectById(int id);
void insert(User user);
void update(User user);
void delete(int id);
}
17、@SpringBootTest
@SpringBootTest 是 Spring Boot 框架中的一个注解,用于测试 Spring Boot 应用程序。它提供了一种便捷的方式来集成 Spring Boot 的自动配置和依赖注入功能,使得测试更加容易和快速。
@SpringBootTest
public class MyApplicationTests {
@Autowired
private MyService myService;
@Test
public void testMyService() {
// 使用 myService 进行测试
}
}
18、@RestControllerAdvice
@RestControllerAdvice = @ControllerAdvice + @ResponseBody,用于定义全局异常处理器
@RestControllerAdvice // @RestControllerAdvice = @ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {
...
}
19、@ExceptionHandler
与@RestControllerAdvice一起使用,用于捕获异常
@RestControllerAdvice // @RestControllerAdvice = @ControllerAdvice + @ResponseBody
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class) // 捕获所有异常
public Result ex(Exception ex) {
ex.printStackTrace();
return Result.error("操作失败,请联系管理员!!!");
}
}
20、@ConditionalOnMissingBean
用于在容器中不存在指定类型的 Bean 时,才会创建被注解的 Bean。
这个注解通常用在 Spring Boot 的自动配置中,以确保某个 Bean 只在容器中没有其他同类型的 Bean 时才会被创建。这对于避免重复配置和确保唯一实例的场景非常有用。
@Bean
@ConditionalOnMissingBean(MessagingConfig.class)
public MessagingConfig messagingConfig() {
return new MessagingConfig();
}
21、@ConfigurationProperties
用于将外部的配置(如 application.properties 或 application.yml 文件中的属性)绑定到 Java 对象上。这个注解主要用于简化配置和整合,使我们可以直接使用 Java 对象来访问配置属性,而不是通过键值对的方式。
myapp.name=My Application
myapp.version=1.0
@Data
@Component
@ConfigurationProperties(prefix = "myapp")
public class MyAppProperties {
private String name;
private String version;
}
现在,当 Spring Boot 启动时,它会将 myapp.name 和 myapp.version 属性自动绑定到 MyAppProperties 类的 name 和 version 属性上。我们可以通过直接访问这些属性的 getter 和 setter 方法来获取和设置它们的值。
22、@EnableTransactionManagement
@EnableTransactionManagement是Spring框架中的一个注解,用于启用事务管理功能。当你在Spring应用程序的配置类上添加此注解时,Spring将开启对@Transactional注解的支持,使你在方法或类上添加@Transactional注解后,Spring能够捕获该注解并自动处理事务。
@SpringBootApplication
@EnableTransactionManagement //开启注解方式的事务管理
@Slf4j
public class SkyApplication {
public static void main(String[] args) {
SpringApplication.run(SkyApplication.class, args);
log.info("server started");
}
}
一般配置在主启动类上,开启注解事务的支持
23、@JsonFormat
用来指定日期和时间的格式
import com.fasterxml.jackson.annotation.JsonFormat;
import java.util.Date;
public class MyObject {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime myDate;
// getter and setter
}
在上面的示例中,myDate字段被标记为@JsonFormat,并指定了日期格式为"yyyy-MM-dd HH:mm:ss"。当将该对象序列化为JSON时,myDate字段将按照指定的格式进行序列化。当从JSON反序列化回Java对象时,Jackson库将使用指定的格式来解析日期。