1、@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

  @RequestMapping 注解提供路由信息。它告诉Spring任何来自"/"路径的HTTP请求都应该被映射到 home 方法。

  @RestController 注解告诉Spring以字符串的形式渲染结果,并直接返回给调用者。

  注: @RestController 和 @RequestMapping 注解是Spring MVC注解(它们不是Spring Boot的特定部分)

2、@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 注解的排除属性来禁用它们。

import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}

  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)})
@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);
}
}

  Spring Boot将尝试校验外部的配置,默认使用JSR-303(如果在classpath路径中)。你可以轻松的为你的@ConfigurationProperties类添加JSR-303 javax.validation约束注解

@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 {
// ...
}@ResponseBody

  表示该方法的返回结果直接写入HTTP response body中

  一般在异步获取数据时使用,在使用@RequestMapping后,返回值通常解析为跳转路径,加上@responsebody后返回结果不会被解析为跳转路径,而是直接写入HTTP response body中。比如:异步获取json数据,加上@responsebody后,会直接返回json数据

3、@Component:

  泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。一般公共的方法我会用上这个注解

4、@AutoWired

  byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。

  当加上(required=false)时,就算找不到bean也不报错。

5、@RequestParam:

  用在方法的参数前面。

@RequestParam String a =request.getParameter("a")

6、@PathVariable:

  路径变量

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;//自动装配service类
@Autowired
OperatorService operatorService;
/**
* 添加活动评论;
*
* @param applyId 活动 ID;
* @param content 评论内容;
* @return
*/
@ResponseBody //异步获取json数据,加上@ResponseBody后直接返回json数据
@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) {
}

  全局处理异常的:

7、@ControllerAdvice:

  包含@Component。可以被扫描到。

  统一处理异常。

8、@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;
}}

9、@value

  通过@value注解来读取application.properties里面的配置

# 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;所以一般常用的配置都是配置在application.properties文件的

spring boot常用注解使用小结的更多相关文章

  1. Spring Boot常用注解总结

    Spring Boot常用注解总结 @RestController和@RequestMapping注解 @RestController注解,它继承自@Controller注解.4.0之前的版本,Spr ...

  2. Spring Boot 常用注解汇总

    一.启动注解 @SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documen ...

  3. Spring Boot常用注解

    SpringBoot注解大全   一.注解(annotations)列表 @SpringBootApplication:包含了@ComponentScan.@Configuration和@Enable ...

  4. spring boot 常用注解

    @RestController和@RequestMapping注解 4.0重要的一个新的改进是@RestController注解,它继承自@Controller注解.4.0之前的版本,spring M ...

  5. spring boot常用注解小计

    @Async 需要执行异步方法时,在方法上加上@Async之后,底层使用多线程技术 .启动类上需要加上 @EnableAsync 注意:异步执行方法,不能与引用方法同在一个类里 @Transactio ...

  6. spring 、spring boot 常用注解

    @Profile 1.用户配置文件注解. 2.使用范围: @Configration 和 @Component 注解的类及其方法, 其中包括继承了 @Component 的注解: @Service. ...

  7. spring boot——常用注解

    @SpringBootApplication:申明让spring boot自动给程序进行必要的配置,这个配置等同于:@Configuration ,@EnableAutoConfiguration 和 ...

  8. (一)Spring Boot 常用注解

    文章目录 一.注解(annotations)列表 二.注解(annotations)详解 三.JPA注解 四.SpringMVC相关注解 五.全局异常处理 @ExceptionHandler(Exce ...

  9. Spring Boot常用注解和原理整理

    一.启动注解 @SpringBootApplication @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documen ...

随机推荐

  1. 洛谷P1154 奶牛分厩

    P1154 奶牛分厩 173通过 481提交 题目提供者该用户不存在 标签高性能 难度普及- 时空限制1s / 128MB 提交  讨论  题解 最新讨论更多讨论 测试点3??? 求助!超时了 我抗议 ...

  2. nc工具学习

    0x00.命令详解 基本使用 想要连接到某处:nc  [-options] ip port 绑定端口等待连接:nc -l -p port ip 参数: -e prog 程序重定向,一旦连接,就执行 [ ...

  3. Linux-UDP-Socket编程

    接收CAN总线上的数据并将其发送出去 创建客户端: /******************************************************************** * co ...

  4. [leetcode greedy]45. Jump Game II

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  5. 深入理解ajax系列第七篇

    前面的话 虽然ajax全称是asynchronous javascript and XML.但目前使用ajax技术时,传递JSON已经成为事实上的标准.因为相较于XML而言,JSON简单且方便.本文将 ...

  6. 【BZOJ 4558】 4558: [JLoi2016]方 (计数、容斥原理)

    未经博主同意不能转载 4558: [JLoi2016]方 Time Limit: 20 Sec  Memory Limit: 256 MBSubmit: 362  Solved: 162 Descri ...

  7. curl_get和curl_post,伪造请求头,绕过防盗链下载文件

    //curl-get function curl_get($url, $timeout = 10) { $ch = curl_init();//初始化 curl_setopt($ch, CURLOPT ...

  8. collection 和 collections

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha collection 是集合的意思. 集合 是 集合类的上级接口, 比如 set 和 l ...

  9. 洛谷.4238.[模板]多项式求逆(NTT)

    题目链接 设多项式\(f(x)\)在模\(x^n\)下的逆元为\(g(x)\) \[f(x)g(x)\equiv 1\ (mod\ x^n)\] \[f(x)g(x)-1\equiv 0\ (mod\ ...

  10. [Arc063F] Snuke's Coloring 2

    [Arc063F] Snuke's Coloring 2 题目大意 给你一个网格图,一些点上有标记,求边长最大空白矩形. 试题分析 专门卡\(\log^2 n\)系列. 首先由题意我们可以找到答案的下 ...