首頁 > Java > java教程 > 主體

總結java中最常用的幾個註解

Y2J
發布: 2017-05-16 09:42:16
原創
1541 人瀏覽過

這篇文章主要介紹了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中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!