1. 程式人生 > >speingboot註解詳細介紹

speingboot註解詳細介紹

註解(annotations)列表

(1)@SpringBootApplication:包含了@ComponentScan,@Configuration和@EnableAutoConfiguration註解註解,其中@ComponentScan讓spring boot掃描到Configuration類並把它加入到程式上下文。

(2)@Configuration 等同於spring的XML配置檔案;使用java程式碼可以檢查類別安全。

(3)@EnableAutoConfiguration自動配置

(4)@ComponentScsn 元件掃描,可自動發現和裝配一些Bean。

(5)@Component可配合CommandLineRunner使用,在程式啟動後執行一些基礎任務。

(6)@RestController註解是@Controller和@ResponseBody的合集,表示這是個控制器Bean,並且是將函式的返回值直接填入HTTP響應體中,是REST風格的控制器。

(7)@Autowired自動注入。

(8)PathVariable 獲取引數。

(9)JsonBackReference解決巢狀外鏈問題。

(10) @RepositoryRestResourcepublic配合spring-boot-starter-data-rest使用。

                                                    註解(annotations)詳解

@SpringBootApplication:申明讓spring boot自動給程式進行必要的配置,這個配置等同於:@Configuration,@EnableAutoConfiguration和@ComponentScan三個配置。

  1.   package com.example.myproject;
  2.   import org.springframework.boot.SpringApplication;
  3.   import org.springframework.boot.autoconfigure.SpringBootApplication;
  4.    
  5.   @SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
  6.   public class Application {
  7.   public static void main(String[] args) {
  8.   SpringApplication.run(Application.class, args);}
  9.   }

  @ResponseBody:表示該方法的返回結果直接寫入HTTP response body中,一般在非同步獲取資料時使用,用於構建RESTful的API。在使用@ResquestMapping後,返回值通常解析為跳轉路徑,加上@ResponseBody後返回結果不會被解析為跳轉路徑,直接寫入HTTP response body中。比如非同步獲取json資料,加上@Responsebody後,會直接返回json資料。該註解一般會配合@RequestMappin一起使用。示例程式碼如下:

  1.   @RequestMapping(“/test”)
  2.   @ResponseBody
  3.   public String test(){
  4.   return”index”;
  5.   }

@Controller:用於定義控制器類,在spring專案中控制器負責將使用者發來的URL請求轉發到對應的介面服務(service層),一般這個註解在類中,通常方法需要配合註解@RequestMapping使用,例如下面程式碼:

  1.   @Controller
  2.   @RequestMapping(“/demo”)
  3.   publicclass DemoController {
  4.   @Autowired
  5.   private DemoInfoService demoInfoService;
  6.    
  7.   @RequestMapping("/hello")
  8.   public String hello(Map<String,Object> map){
  9.   System. out.println("DemoController.hello()");
  10.   map.put( "hello","from TemplateController.helloHtml");
  11.   //會使用hello.html或者hello.ftl模板進行渲染顯示.
  12.   return"/hello";}
  13.   }

@RestController:用於標註控制層元件(如struts中的action),@ResponseBody和@Controller的合集。@RestController = @ResponseBody + @Controller。例項如下:

  1.   package com.kfit.demo.web;
  2.    
  3.   import org.springframework.web.bind.annotation.RequestMapping;
  4.   import org.springframework.web.bind.annotation.RestController;
  5.    
  6.   @ RestController
  7.   @RequestMapping(“/demoInfo2”)
  8.   publicclass DemoController2 {
  9.   @ RequestMapping("/test")
  10.   public String test(){
  11.   return"ok";
  12.   }
  13.   }

@RequestMapping:提供路由資訊,負責URL到Controller中的具體函式的對映。

@EnableAutoConfiguration:springboot自動配置(auto-configuration):嘗試根據你新增的jar依賴自動配置你的spring應用。 

如果你的calsspath下存在HSALDB,並且你沒有手動配置任何資料庫連線的beans,那麼我們將自動配置一個記憶體型(in-memory)資料庫。可以將@EnableAutoConfiguration或者@SpringBootApplication註解新增到一個@Configuration類上來選擇自動配置。如果發現應用了不想要的特定自動配置類,可是使用@EnableAutoConfiguration註解的排除屬性類禁用它們。

@ComponentScan:表示將該類自動發現掃描元件。

掃描到有@Component,@Controller,[email protected]等這些註解的類,並註冊為Bean,可以自動收集所有的Spring元件,包括@Configuration註解的類。經常使用@ComponentScan註解搜尋beans,並結合@Autowried註解匯入。如果沒有配置的話,Spring boot會掃描自動類所在包下以及子包下使用了@Service,@Respository等註解的類。

@Configuration:相當於傳統的xml配置檔案,如果有些第三方庫需要用到xml檔案,建議仍然[email protected]註解的類作為專案的配置主類-------可以使用@ImportResouce註解和載入xml配置檔案。

@Import:用來匯入其它配置類。

@ImpoertResouce:用來載入xml配置檔案。

@AutoWired:自動匯入依賴的bean.

@Service:一般用於修飾service層的元件。

@Autowired:自動匯入依賴的bean.

@Repository:使用@Repository註解可以確保DAO或者respositories提供異常轉譯,這個註解修飾的DAO或者respositories類會被CompoonentScan返現並配置,同時也不需要為他們提供XML配置項。

@Bean:用於@Bean標註方法等價於XML中配置的bean.

@Value:注入Spring boot application.properties配置的屬性的值。示例程式碼:

@Value(value = "#{message}")

private String message;

@Inject:等價於預設的@Autowried,只是沒喲required屬性。

@Component:泛指元件,當元件不好歸類的時候,我們可以使用這個註解進行標註。

@Bean:相當於XML中的,放在方法的上面。、而不是類,意思是產生一個bean,並交給spring管理。

@AutoWired:自動匯入依賴的bean,byType,方式。把配置好的Bean拿來用,完成屬性,方法的組裝,它可以對類成員變數。方法以及建構函式進行標註,完成自動裝配工作。黨加上(required = false)時,就算找不到bean也不報錯。

@Qualifier:當有多個同意型別的bean時,可以用@Qualifier("name")來指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據名字進行注入,但能進行更細粒度的控制如何選擇候選者,具體使用方式如下:

  1.   @Autowired
  2.   @Qualifier(value = “demoInfoService”)
  3.   private DemoInfoService demoInfoService;
    • @Resource(name=”name”,type=”type”):沒有括號內內容的話,預設byName。與@Autowired幹類似的事。

      三、JPA註解

    • @Entity:@Table(name=”“):表明這是一個實體類。一般用於jpa這兩個註解一般一塊使用,但是如果表名和實體類名相同的話,@Table可以省略

    • @MappedSuperClass:用在確定是父類的entity上。父類的屬性子類可以繼承。

    • @NoRepositoryBean:一般用作父類的repository,有這個註解,spring不會去例項化該repository。

    • @Column:如果欄位名與列名相同,則可以省略。

    • @Id:表示該屬性為主鍵。

    • @GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主鍵生成策略是sequence(可以為Auto、IDENTITY、native等,Auto表示可在多個數據庫間切換),指定sequence的名字是repair_seq。

    • 四、springMVC相關注解

      @RequestMapping:@RequestMapping(“/path”)表示該控制器處理所有“/path”的UR L請求。RequestMapping是一個用來處理請求地址對映的註解,可用於類或方法上。
      用於類上,表示類中的所有響應請求的方法都是以該地址作為父路徑。該註解有六個屬性:

    • params:指定request中必須包含某些引數值是,才讓該方法處理。

    • headers:指定request中必須包含某些指定的header值,才能讓該方法處理請求。

    • value:指定請求的實際地址,指定的地址可以是URI Template 模式

    • method:指定請求的method型別, GET、POST、PUT、DELETE等

    • consumes:指定處理請求的提交內容型別(Content-Type),如application/json,text/html;

    • produces:指定返回的內容型別,僅當request請求頭中的(Accept)型別中包含該指定型別才返回

      1.   @RequestParam:用在方法的引數前面。
      2.   @RequestParam
      3.   String a =request.getParameter(“a”)。
      4.    
      5.   @PathVariable:路徑變數。如
      6.   RequestMapping(“user/ get/mac/{macAddress}”)
      7.   public String getByMacAddress(@PathVariable String macAddress){
      8.   //do something;
      9.   }
      10.   引數與大括號裡的名字一樣要相同。

      五、全域性異常處理

    • @ControllerAdvice:包含@Component。可以被掃描到。統一處理異常。

    • @ExceptionHandler(Exception.class):用在方法上面表示遇到這個異常就執行以下方法。

    •  
    • @SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name為sequence的名稱,以便使用,sequenceName為資料庫的sequence名稱,兩個名稱可以一致。

    • @Transient:表示該屬性並非一個到資料庫表的欄位的對映,ORM框架將忽略該屬性。如果一個屬性並非資料庫表的欄位對映,就務必將其標示為@Transient,否則,ORM框架預設其註解為@Basic。@Basic(fetch=FetchType.LAZY):標記可以指定實體屬性的載入方式

    • @JsonIgnore:作用是json序列化時將java bean中的一些屬性忽略掉,序列化和反序列化都受影響。

    • @JoinColumn(name=”loginId”):一對一:本表中指向另一個表的外來鍵。一對多:另一個表指向本表的外來鍵。

    • @OneToOne、@OneToMany、@ManyToOne:對應Hibernate配置檔案中的一對一,一對多,多對一。