这篇文章主要介绍了spring boot 的常用注解使用小结,需要的朋友可以参考下
@RestController和@RequestMapping注解
4.0重要的一个新的改进是@RestController注解,它继承自@Controller注解。4.0之前的版本,Spring MVC的组件都使用@Controller来标识当前类是一个控制器servlet。使用这个特性,我们可以开发REST服务的时候不需要使用@Controller而专门的@RestController。
当你实现一个RESTful web services的时候,response将一直通过response body发送。为了简化开发,Spring 4.0提供了一个专门版本的controller。下面我们来看看@RestController实现的定义:
@Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Controller @ResponseBody public @interface RestController @Target(value=TYPE) @Retention(value=RUNTIME) @Documented @Controller @ResponseBody public @interface RestController
@RequestMapping 注解提供路由信息。它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到 home 方法。 @RestController 注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。
注: @RestController 和 @RequestMapping 注解是Spring MVC注解(它们不是Spring Boot的特定部分)
@EnableAutoConfiguration注解
第二个类级别的注解是 @EnableAutoConfiguration 。这个注解告诉Spring Boot根据添加的jar依赖猜测你想如何配置Spring。由于 spring-boot-starter-web 添加了Tomcat和Spring MVC,所以auto-configuration将假定你正在开发一个web应用并相应地对Spring进行设置。Starter POMs和Auto-Configuration:设计auto-configuration的目的是更好的使用"Starter POMs",但这两个概念没有直接的联系。你可以自由地挑选starter POMs以外的jar依赖,并且Spring Boot将仍旧尽最大努力去自动配置你的应用。
你可以通过将 @EnableAutoConfiguration 或 @SpringBootApplication 注解添加到一个 @Configuration 类上来选择自动配置。
注:你只需要添加一个 @EnableAutoConfiguration 注解。我们建议你将它添加到主 @Configuration 类上。
如果发现应用了你不想要的特定自动配置类,你可以使用 @EnableAutoConfiguration 注解的排除属性来禁用它们。
<pre name="code" class="java">import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration { } <pre name="code" class="java">import org.springframework.boot.autoconfigure.*; import org.springframework.boot.autoconfigure.jdbc.*; import org.springframework.context.annotation.*; @Configuration @EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) public class MyConfiguration { } @Configuration
Spring Boot提倡基于Java的配置。尽管你可以使用一个XML源来调用 SpringApplication.run() ,我们通常建议你使用 @Configuration 类作为主要源。一般定义 main 方法的类也是主要 @Configuration 的一个很好候选。你不需要将所有的 @Configuration 放进一个单独的类。 @Import 注解可以用来导入其他配置类。另外,你也可以使用 @ComponentScan 注解自动收集所有的Spring组件,包括 @Configuration 类。
如果你绝对需要使用基于XML的配置,我们建议你仍旧从一个 @Configuration 类开始。你可以使用附加的 @ImportResource 注解加载XML配置文件。
@Configuration注解该类,等价 与XML中配置beans;用@Bean标注方法等价于XML中配置bean
@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)}) @ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)}) @SpringBootApplication
很多Spring Boot开发者总是使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 注解他们的main类。由于这些注解被如此频繁地一块使用(特别是你遵循以上最佳实践时),Spring Boot提供一个方便的 @SpringBootApplication 选择。
该 @SpringBootApplication 注解等价于以默认属性使用 @Configuration , @EnableAutoConfiguration 和 @ComponentScan 。
package com.example.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } package com.example.myproject; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解:
@Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings { @NotNull private InetAddress remoteAddress; // ... getters and setters } @Component @ConfigurationProperties(prefix="connection") public class ConnectionSettings { @NotNull private InetAddress remoteAddress; // ... getters and setters } @Profiles Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。任何@Component或@Configuration都能被@Profile标记,从而限制加载它的时机。 [java] view plain copy print?在CODE上查看代码片派生到我的代码片 @Configuration @Profile("production") public class ProductionConfiguration { // ... } @Configuration @Profile("production") public class ProductionConfiguration { // ... }@ResponseBody
表示该方法的返回结果直接写入HTTP response body中
一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上
@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如
异步获取json数据,加上@responsebody后,会直接返回json数据。
@Component:
泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。一般公共的方法我会用上这个注解
@AutoWired
byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构
造函数进行标注,完成自动装配的工作。
当加上(required=false)时,就算找不到bean也不报错。
@RequestParam:
用在方法的参数前面。
@RequestParam String a =request.getParameter("a")。 @RequestParam String a =request.getParameter("a")。
@PathVariable:
路径变量。
RequestMapping("user/get/mac/{macAddress}") public String getByMacAddress(@PathVariable String macAddress){ //do something; } RequestMapping("user/get/mac/{macAddress}") public String getByMacAddress(@PathVariable String macAddress){ //do something; }
参数与大括号里的名字一样要相同。
以上注解的示范
/** * 用户进行评论及对评论进行管理的 Controller 类; */ @Controller @RequestMapping("/msgCenter") public class MyCommentController extends BaseController { @Autowired CommentService commentService; @Autowired OperatorService operatorService; /** * 添加活动评论; * * @param applyId 活动 ID; * @param content 评论内容; * @return */ @ResponseBody @RequestMapping("/addComment") public Map<String, Object> addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) { .... return result; } } /** * 用户进行评论及对评论进行管理的 Controller 类; */ @Controller @RequestMapping("/msgCenter") public class MyCommentController extends BaseController { @Autowired CommentService commentService; @Autowired OperatorService operatorService; /** * 添加活动评论; * * @param applyId 活动 ID; * @param content 评论内容; * @return */ @ResponseBody @RequestMapping("/addComment") public Map<String, Object> addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) { .... return result; } } @RequestMapping("/list/{applyId}") public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) { } @RequestMapping("/list/{applyId}") public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) { }
全局处理异常的:
@ControllerAdvice:
包含@Component。可以被扫描到。
统一处理异常。
@ExceptionHandler(Exception.class):
用在方法上面表示遇到这个异常就执行以下方法。
/** * 全局异常处理 */ @ControllerAdvice class GlobalDefaultExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler({TypeMismatchException.class,NumberFormatException.class}) public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("error","参数类型错误"); mav.addObject("exception", e); mav.addObject("url", RequestUtils.getCompleteRequestUrl(req)); mav.addObject("timestamp", new Date()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; }} /** * 全局异常处理 */ @ControllerAdvice class GlobalDefaultExceptionHandler { public static final String DEFAULT_ERROR_VIEW = "error"; @ExceptionHandler({TypeMismatchException.class,NumberFormatException.class}) public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception { ModelAndView mav = new ModelAndView(); mav.addObject("error","参数类型错误"); mav.addObject("exception", e); mav.addObject("url", RequestUtils.getCompleteRequestUrl(req)); mav.addObject("timestamp", new Date()); mav.setViewName(DEFAULT_ERROR_VIEW); return mav; }}
通过@value注解来读取application.properties里面的配置
# face++ key face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR**** face_api_secret =D9WUQGCYLvOCIdsbX35uTH******** # face++ key face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR**** face_api_secret =D9WUQGCYLvOCIdsbX35uTH******** @Value("${face_api_key}") private String API_KEY; @Value("${face_api_secret}") private String API_SECRET; @Value("${face_api_key}") private String API_KEY; @Value("${face_api_secret}") private String API_SECRET;所以一般常用的配置都是配置在application.properties文件的
【相关推荐】
1. 特别推荐:“php程序员工具箱”V0.1版本下载
2. Java免费视频教程
3. JAVA教程手册
以上是总结java中最常用的几个注解的详细内容。更多信息请关注PHP中文网其他相关文章!

java实现定时任务Jdk自带的库中,有两种方式可以实现定时任务,一种是Timer,另一种是ScheduledThreadPoolExecutor。Timer+TimerTask创建一个Timer就创建了一个线程,可以用来调度TimerTask任务Timer有四个构造方法,可以指定Timer线程的名字以及是否设置为为守护线程。默认名字Timer-编号,默认不是守护线程。主要有三个比较重要的方法:cancel():终止任务调度,取消当前调度的所有任务,正在运行的任务不受影响purge():从任务队

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

SpringBoot和SpringCloud都是SpringFramework的扩展,它们可以帮助开发人员更快地构建和部署微服务应用程序,但它们各自有不同的用途和功能。SpringBoot是一个快速构建Java应用的框架,使得开发人员可以更快地创建和部署基于Spring的应用程序。它提供了一个简单、易于理解的方式来构建独立的、可执行的Spring应用

随着技术的更新迭代,Java5.0开始支持注解。而作为java中的领军框架spring,自从更新了2.5版本之后也开始慢慢舍弃xml配置,更多使用注解来控制spring框架。

1.Spring项目的创建1.1创建Maven项目第一步,创建Maven项目,Spring也是基于Maven的。1.2添加spring依赖第二步,在Maven项目中添加Spring的支持(spring-context,spring-beans)在pom.xml文件添加依赖项。org.springframeworkspring-context5.2.3.RELEASEorg.springframeworkspring-beans5.2.3.RELEASE刷新等待加载完成。1.3创建启动类第三步,创

作为一名Java开发者,学习和使用Spring框架已经是一项必不可少的技能。而随着云计算和微服务的盛行,学习和使用SpringCloud成为了另一个必须要掌握的技能。SpringCloud是一个基于SpringBoot的用于快速构建分布式系统的开发工具集。它为开发者提供了一系列的组件,包括服务注册与发现、配置中心、负载均衡和断路器等,使得开发者在构建微

SpringBean的生命周期管理一、SpringBean的生命周期通过以下方式来指定Bean的初始化和销毁方法,当Bean为单例时,Bean归Spring容器管理,Spring容器关闭,就会调用Bean的销毁方法当Bean为多例时,Bean不归Spring容器管理,Spring容器关闭,不会调用Bean的销毁方法二、通过@Bean的参数(initMethod,destroyMethod)指定Bean的初始化和销毁方法1、项目结构2、PersonpublicclassPerson{publicP

spring设计模式有:1、依赖注入和控制反转;2、工厂模式;3、模板模式;4、观察者模式;5、装饰者模式;6、单例模式;7、策略模式和适配器模式等。详细介绍:1、依赖注入和控制反转: 这两个设计模式是Spring框架的核心。通过依赖注入,Spring负责管理和注入组件之间的依赖关系,降低了组件之间的耦合度。控制反转则是指将对象的创建和依赖关系的管理交给Spring容器等等。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

DVWA
Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

Atom编辑器mac版下载
最流行的的开源编辑器