spring boot学习 ---- spring boot 之注解(持续更新)
这里介绍
@Controller
(类)声明控制器,它是
@ResponseBody
(方法、类)响应
@RestController
(类)相当于同时添加
@RequestMapping
(类、方法)提供“路由”信息。它告诉
@EnableAutoConfiguration
(类)这个注释告诉
@ComponentScan
(类)这个注释
@SpringBootApplication
(类)通常在启动类上添加这个注解。它包括
ps:相当于
@Configuration
(类)
@Import
(类)通常我们不必将所有配置放在一个类中,我们可以通过
@ImportResource
(类)导入
@PropertySource
(类)加载配置文件到项目中。
@Component @Service @Repository @Controller
(类)使用这些均是将该类声明成一个组件。程序会将这个组件交给
其中
@Autowried
(字段、构造方法、方法、注解、参数)被改注解声明的变量将会被自动注入一个对象。
@Before、@After、@Around、@AfterReturn、@AfterThrowing
(方法)被这几个注解标记的方法是用在
@PointCut
(方法)被该注解标记的方法被声明成一个切入点,这样我们可以简化切入点的编写。
@Aspect
(类)该注解表示该类是一个能够使用
@Value
(字段,方法,注解,参数)从配置文件中载入数据
格式:@Value("${xxxx.xxx}")
@ConfigurationProperties
(类、方法)加载配置文件,可以批量注入配置到对象中,需要额外添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
使用例子:
@ConfigurationProperties(prefix="acme")
@Validated
public class AcmeProperties {
@NotNull
private InetAddress remoteAddress;
@Valid
private final Security security = new Security();
// ... getters and setters
public static class Security {
@NotEmpty
public String username;
// ... getters and setters
}
}
@Profile
(类、方法)
@JsonComponent
(类)如果使用
@Bean
(方法、注解)
@ControllerAdvice、@ExceptionHandler
(类)您还可以定义一个用
(方法)@ExceptionHandler
- 一个
Controller 下多个@ExceptionHandler 上的异常类型不能出现一样的,否则运行时抛异常. - 方法返回值类型支持多种,常见的
ModelAndView ,@ResponseBody 注解标注,ResponseEntity 等类型都OK.
例如:
@ControllerAdvice(basePackageClasses = AcmeController.class)
public class AcmeControllerAdvice extends ResponseEntityExceptionHandler {
@ExceptionHandler(YourException.class)
@ResponseBody
ResponseEntity<?> handleControllerException(HttpServletRequest request, Throwable ex) {
HttpStatus status = getStatus(request);
return new ResponseEntity<>(new CustomErrorType(status.value(), ex.getMessage()), status);
}
private HttpStatus getStatus(HttpServletRequest request) {
Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
if (statusCode == null) {
return HttpStatus.INTERNAL_SERVER_ERROR;
}
return HttpStatus.valueOf(statusCode);
}
}
@CrossOrigin
(类、方法)允许跨域,但一般会写成配置文件的格式
@Configuration
public class MyConfiguration {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**");
}
};
}
}
@EnableWebFlux
(类) 开启webFlux
不能与springMVC
同时存在
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· 因为Apifox不支持离线,我果断选择了Apipost!