日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot注解大全

發(fā)布時(shí)間:2025/3/15 javascript 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot注解大全 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

使用注解的優(yōu)勢(shì):

  • 1.采用純java代碼,不在需要配置繁雜的xml文件

  • 2.在配置中也可享受面向?qū)ο髱淼暮锰?/p>

  • 3.類型安全對(duì)重構(gòu)可以提供良好的支持

  • 4.減少復(fù)雜配置文件的同時(shí)亦能享受到springIoC容器提供的功能

一、注解詳解(配備了完善的釋義)

  • @SpringBootApplication:申明讓spring boot自動(dòng)給程序進(jìn)行必要的配置,這個(gè)配置等同于:
  • @Configuration ,@EnableAutoConfiguration 和 @ComponentScan 三個(gè)配置。

  • @ResponseBody:表示該方法的返回結(jié)果直接寫入HTTP response body中,一般在異步獲取數(shù)據(jù)時(shí)使用,用于構(gòu)建RESTful的api。在使用@RequestMapping后,返回值通常解析為跳轉(zhuǎn)路徑,加上@esponsebody后返回結(jié)果不會(huì)被解析為跳轉(zhuǎn)路徑,而是直接寫入HTTP response body中。比如異步獲取json數(shù)據(jù),加上@Responsebody后,會(huì)直接返回json數(shù)據(jù)。該注解一般會(huì)配合@RequestMapping一起使用。

  • @Controller:用于定義控制器類,在spring項(xiàng)目中由控制器負(fù)責(zé)將用戶發(fā)來的URL請(qǐng)求轉(zhuǎn)發(fā)到對(duì)應(yīng)的服務(wù)接口(service層),一般這個(gè)注解在類中,通常方法需要配合注解@RequestMapping。

  • @RestController:用于標(biāo)注控制層組件(如struts中的action),@ResponseBody和@Controller的合集。

  • @RequestMapping:提供路由信息,負(fù)責(zé)URL到Controller中的具體函數(shù)的映射。

  • @CrossOrigin:是Cross-Origin ResourceSharing(跨域資源共享)的簡(jiǎn)寫,作用是解決跨域訪問的問題,在Spring4.2以上的版本可直接使用。在類上或方法上添加該注解

  • @CrossOrigin public class TestController extends BaseController { XXXX }

    如果失效則可能方法沒解決是GET還是POST方式,指定即可解決問題。
    7. @RequestParam:作用是提取和解析請(qǐng)求中的參數(shù)。@RequestParam支持類型轉(zhuǎn)換,類型轉(zhuǎn)換目前支持所有的基本Java類型

    @RequestParam([value="number"], [required=false]) String number

    將請(qǐng)求中參數(shù)為number映射到方法的number上。required=false表示該參數(shù)不是必需的,請(qǐng)求上可帶可不帶。

  • @PathVariable,@RequestHeader,@CookieValue,@RequestParam, @RequestBody,@SessionAttributes, @ModelAttribute
  • @PathVariable:處理requet uri部分,當(dāng)使用@RequestMapping URI template 樣式映射時(shí), 即someUrl/{paramId}, 這時(shí)的paramId可通過 @Pathvariable注解綁定它傳過來的值到方法的參數(shù)上

    例如:

    @Controller @RequestMapping("/owners/{a}") public class RelativePathUriTemplateController { @RequestMapping("/pets/") public void findPet(@PathVariable("a") String a,@PathVariable String b, Model model) { // implementation omitted } }@RequestHeader@CookieValue: 處理request header部分的注解將頭部信息綁定到方法參數(shù)上:@RequestMapping("/test") public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive")long keepAlive) { //... }//將cookie里JSESSIONID綁定到方法參數(shù)上@RequestMapping("/test") public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) { //... }
  • @EnableAutoConfiguration:SpringBoot自動(dòng)配置(auto-configuration):嘗試根據(jù)你添加的jar依賴自動(dòng)配置你的Spring應(yīng)用。例如,如果你的classpath下存在HSQLDB,并且你沒有手動(dòng)配置任何數(shù)據(jù)庫連接beans,那么我們將自動(dòng)配置一個(gè)內(nèi)存型(in-memory)數(shù)據(jù)庫”。你可以將@EnableAutoConfiguration或者@SpringBootApplication注解添加到一個(gè)@Configuration類上來選擇自動(dòng)配置。如果發(fā)現(xiàn)應(yīng)用了你不想要的特定自動(dòng)配置類,你可以使用@EnableAutoConfiguration注解的排除屬性來禁用它們。

  • @ComponentScan:表示將該類自動(dòng)發(fā)現(xiàn)掃描組件。個(gè)人理解相當(dāng)于,如果掃描到有@Component、@Controller、@Service等這些注解的類,并注冊(cè)為Bean,可以自動(dòng)收集所有的Spring組件,包括@Configuration類。我們經(jīng)常使用@ComponentScan注解搜索beans,并結(jié)合@Autowired注解導(dǎo)入??梢宰詣?dòng)收集所有的Spring組件,包括@Configuration類。如果沒有配置的話,Spring Boot會(huì)掃描啟動(dòng)類所在包下以及子包下的使用了@Service,@Repository等注解的類。

  • @Configuration:相當(dāng)于傳統(tǒng)的xml配置文件,如果有些第三方庫需要用到xml文件,建議仍然通過@Configuration類作為項(xiàng)目的配置主類——可以使用@ImportResource注解加載xml配置文件。

  • @Configuration public class MainConfig {//在properties文件里配置@Value("${wx_appid}")public String appid;protected MainConfig(){}@Bean public WxMpService wxMpService() {WxMpService wxMpService = new WxMpServiceImpl();wxMpService.setWxMpConfigStorage(wxMpConfigStorage());return wxMpService;} }
  • @Import:用來導(dǎo)入其他配置類。

  • @ImportResource:用來加載xml配置文件。

  • @AutoWired:自動(dòng)導(dǎo)入依賴的bean。byType方式。把配置好的Bean拿來用,完成屬性、方法的組裝,它可以對(duì)類成員變量、方法及構(gòu)造函數(shù)進(jìn)行標(biāo)注,完成自動(dòng)裝配的工作。當(dāng)加上(required=false)時(shí),就算找不到bean也不報(bào)錯(cuò)。

  • @Qualifier:當(dāng)有多個(gè)同一類型的Bean時(shí),可以用@Qualifier(“name”)來指定。與@Autowired配合使用。@Qualifier限定描述符除了能根據(jù)名字進(jìn)行注入,但能進(jìn)行更細(xì)粒度的控制如何選擇候選者

  • @Resource(name=”name”,type=”type”):沒有括號(hào)內(nèi)內(nèi)容的話,默認(rèn)byName。與@Autowired干類似的事。

  • @Service:一般用于修飾service層的組件

  • @Repository:使用@Repository注解可以確保DAO或者repositories提供異常轉(zhuǎn)譯,這個(gè)注解修飾的DAO或者repositories類會(huì)被ComponetScan發(fā)現(xiàn)并配置,同時(shí)也不需要為它們提供XML配置項(xiàng)。

  • @Bean:用@Bean標(biāo)注方法等價(jià)于XML中配置的bean。

  • @Value:注入Spring boot application.properties配置的屬性的值。

  • @Value("${wx_appid}")public String appid;
  • @Inject:等價(jià)于默認(rèn)的@Autowired,只是沒有required屬性;
  • @Primary:自動(dòng)裝配時(shí)當(dāng)出現(xiàn)多個(gè)Bean候選者時(shí),被注解為@Primary的Bean將作為首選者,否則將拋出異常。
  • @Component public class Apple implements Fruit{ @Override public String hello() { return "我是蘋果"; } } @Component @Primary public class Pear implements Fruit{ @Override public String hello(String lyrics) { return "梨子"; } } public class FruitService {//Fruit有2個(gè)實(shí)例子類,因?yàn)槔孀佑?#64;Primary,那么會(huì)使用Pear注入@Autowired private Fruit fruit; public String hello(){ return fruit.hello(); } }
  • @Component:泛指組件,當(dāng)組件不好歸類的時(shí)候,我們可以使用這個(gè)注解進(jìn)行標(biāo)注。
  • @Lazy(true):用于指定該Bean是否取消預(yù)初始化,用于注解類,延遲初始化。(懶加載)
  • @Async:java里使用線程用3種方法:
    • 繼承Thread,重寫run方法
    • 實(shí)現(xiàn)Runnable,重寫run方法
    • 使用Callable和Future接口創(chuàng)建線程,并能得到返回值。

    前2種簡(jiǎn)單,第3種方式特別提示一下,例子如下:

    class MyCallable implements Callable<Integer> {private int i = 0;// 與run()方法不同的是,call()方法具有返回值@Overridepublic Integer call() {int sum = 0;for (; i < 100; i++) {System.out.println(Thread.currentThread().getName() + " " + i);sum += i;}return sum;} } main方法:public static void main(String[] args) {Callable<Integer> myCallable = new MyCallable(); // 創(chuàng)建MyCallable對(duì)象FutureTask<Integer> ft = new FutureTask<Integer>(myCallable); //使用FutureTask來包裝MyCallable對(duì)象for (int i = 0; i < 100; i++) {System.out.println(Thread.currentThread().getName() + " " + i);if (i == 30) {Thread thread = new Thread(ft); //FutureTask對(duì)象作為Thread對(duì)象的target創(chuàng)建新的線程thread.start(); //線程進(jìn)入到就緒狀態(tài)}}System.out.println("主線程for循環(huán)執(zhí)行完畢..");try {int sum = ft.get(); //取得新創(chuàng)建的新線程中的call()方法返回的結(jié)果System.out.println("sum = " + sum);} catch (InterruptedException e) {e.printStackTrace();} catch (ExecutionException e) {e.printStackTrace();} }

    而使用@Async可視為第4種方法。基于@Async標(biāo)注的方法,稱之為異步方法,這個(gè)注解用于標(biāo)注某個(gè)方法或某個(gè)類里面的所有方法都是需要異步處理的。被注解的方法被調(diào)用的時(shí)候,會(huì)在新線程中執(zhí)行,而調(diào)用它的方法會(huì)在原來的線程中執(zhí)行。

    application.xml形勢(shì)的配置:

    第一步配置XML。

    <!--掃描注解,其中包括@Async --> <context:component-scan base-package="com.test"/> <!-- 支持異步方法執(zhí)行, 指定一個(gè)缺省的executor給@Async使用--> <task:annotation-driven executor="defaultAsyncExecutor" /> <!—配置一個(gè)線程執(zhí)行器--> <task:executor id=" defaultAsyncExecutor "pool-size="100-10000" queue-capacity="10" keep-alive =”5”/>

    參數(shù)解讀:

    配置參數(shù):

    • id:當(dāng)配置多個(gè)executor時(shí),被@Async(“id”)指定使用;也被作為線程名的前綴。

    • pool-size:

    • core size:最小的線程數(shù),缺省:1

    • max size:最大的線程數(shù),缺省:Integer.MAX_VALUE

    • queue-capacity:當(dāng)最小的線程數(shù)已經(jīng)被占用滿后,新的任務(wù)會(huì)被放進(jìn)queue里面,當(dāng)這個(gè)queue的capacity也被占滿之后,pool里面會(huì)創(chuàng)建新線程處理這個(gè)任務(wù),直到總線程數(shù)達(dá)到了max
      size,這時(shí)系統(tǒng)會(huì)拒絕這個(gè)任務(wù)并拋出TaskRejectedException異常(缺省配置的情況下,可以通過rejection-policy來決定如何處理這種情況)。缺省值為:Integer.MAX_VALUE

    • keep-alive:超過core size的那些線程,任務(wù)完成后,再經(jīng)過這個(gè)時(shí)長(zhǎng)(秒)會(huì)被結(jié)束掉

    • rejection-policy:當(dāng)pool已經(jīng)達(dá)到max size的時(shí)候,如何處理新任務(wù)

    • ABORT(缺省):拋出TaskRejectedException異常,然后不執(zhí)行DISCARD:不執(zhí)行,也不拋出異常

    • DISCARD_OLDEST:丟棄queue中最舊的那個(gè)任務(wù)

    • CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來執(zhí)行

    第二步在類或方法上添加@Async,當(dāng)調(diào)用該方法時(shí),則該方法即是用異常執(zhí)行的方法單獨(dú)開個(gè)新線程執(zhí)行。

    @Async(“可以指定執(zhí)行器id,也可以不指定”)public static void testAsyncVoid (){try {//讓程序暫停100秒,相當(dāng)于執(zhí)行一個(gè)很耗時(shí)的任務(wù)System.out.println(“異常執(zhí)行打印字符串”);Thread.sleep(100000);} catch (InterruptedException e) {e.printStackTrace();}}

    當(dāng)在外部調(diào)用testAsync方法時(shí)即在新線程中執(zhí)行,由上面執(zhí)行器去維護(hù)線程。

    總結(jié):先用context:component-scan去掃描注解,讓spring能識(shí)別到@Async注解,然后task:annotation-driven去驅(qū)動(dòng)@Async注解,并可以指定默認(rèn)的線程執(zhí)行器executor。那么當(dāng)用@Async注解的方法或類得到調(diào)用時(shí),線程執(zhí)行器會(huì)創(chuàng)建新的線程去執(zhí)行。

    上面方法是無返回值的情況,還有異常方法有返回值的例子。

    @Async public Future<String> testAsyncReturn () { System.out.println("Execute method asynchronously - " + Thread.currentThread().getName()); try { Thread.sleep(5000); return new AsyncResult<String>("hello world !!!!"); } catch (InterruptedException e) { // } return null; }

    返回的數(shù)據(jù)類型為Future類型,接口實(shí)現(xiàn)類是AsyncResult.

    調(diào)用方法如下:

    public void test(){Future<String> future = cc.testAsyncReturn(); while (true) { ///這里使用了循環(huán)判斷,等待獲取結(jié)果信息 if (future.isDone()) { //判斷是否執(zhí)行完畢 System.out.println("Result from asynchronous process - " + future.get()); break; } System.out.println("Continue doing something else. "); Thread.sleep(1000); } }

    通過不停的檢查Future的狀態(tài)來獲取當(dāng)前的異步方法是否執(zhí)行完畢
    編程的方式使用@Async:

    @Configuration @EnableAsync public class SpringConfig {private int corePoolSize = 10; private int maxPoolSize = 200; private int queueCapacity = 10; private String ThreadNamePrefix = "MyLogExecutor-"; @Bean public Executor logExecutor() { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); executor.setCorePoolSize(corePoolSize); executor.setMaxPoolSize(maxPoolSize); executor.setQueueCapacity(queueCapacity); executor.setThreadNamePrefix(ThreadNamePrefix); // rejection-policy:當(dāng)pool已經(jīng)達(dá)到max size的時(shí)候,如何處理新任務(wù) // CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來執(zhí)行 executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy()); executor.initialize(); return executor; } }
  • @Bean:放在方法的上面,而不是類,意思是產(chǎn)生一個(gè)bean,并交給spring管理。@Bean 用在方法上,告訴Spring容器,你可以從下面這個(gè)方法中拿到一個(gè)Bean
  • @Singleton:只要在類上加上這個(gè)注解,就可以實(shí)現(xiàn)一個(gè)單例類,不需要自己手動(dòng)編寫單例實(shí)現(xiàn)類。
  • @PostConstruct 和 @PreDestory:實(shí)現(xiàn)初始化和銷毀bean之前進(jìn)行的操作,只能有一個(gè)方法可以用此注釋進(jìn)行注釋,方法不能有參數(shù),返回值必需是void,方法需要是非靜態(tài)的。
  • public class TestService { @PostConstruct public void init(){ System.out.println("初始化"); }@PreDestroy public void dostory(){ System.out.println("銷毀"); } }

    流程圖:

    引深一點(diǎn),Spring 容器中的 Bean 是有生命周期的,Spring 允許在 Bean 在初始化完成后以及 Bean 銷毀前執(zhí)行特定的操作,常用的設(shè)定方式有以下三種:

    • 1.通過實(shí)現(xiàn) InitializingBean/DisposableBean 接口來定制初始化之后/銷毀之前的操作方法;
    • 2.通過 元素的 init-method/destroy-method屬性指定初始化之后 /銷毀之前調(diào)用的操作方法;
    • 3.在指定方法上加上@PostConstruct 或@PreDestroy注解來制定該方法是在初始化之后還是銷毀之前調(diào)用,但他們之前并不等價(jià)。即使3個(gè)方法都用上了,也有先后順序.
      Constructor > @PostConstruct >InitializingBean > init-method
  • @ControllerAdvice:
  • 官方解釋是:即把@ControllerAdvice注解內(nèi)部使用@ExceptionHandler、@InitBinder、@ModelAttribute注解的方法應(yīng)用到所有的 @RequestMapping注解的方法。非常簡(jiǎn)單,不過只有當(dāng)使用@ExceptionHandler最有用,另外兩個(gè)用處不大。

    @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(SQLException.class) @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR,reason=”sql查詢錯(cuò)誤”) @ResponseBody public ExceptionResponse handleSQLException(HttpServletRequest request, Exception ex) { String message = ex.getMessage(); return ExceptionResponse.create(HttpStatus.INTERNAL_SERVER_ERROR.value(), message); } }

    即表示讓Spring捕獲到所有拋出的SQLException異常,并交由這個(gè)被注解的handleSQLException方法處理,同時(shí)使用@ResponseStatus指定了code和reason寫到response上,返回給前端。

    二、請(qǐng)求參數(shù)注解

  • 處理requet uri 部分(這里指uri template中variable,不含queryString部分)的注解: @PathVariable;

  • 處理request header部分的注解: @RequestHeader, @CookieValue;

  • 處理request body部分的注解:@RequestParam, @RequestBody;

  • 處理attribute類型是注解: @SessionAttributes, @ModelAttribute;
    其中最常用的是第3種,@RequestParam、@RequestBody

  • application/json:json字符串部分可以用@RequestBody;url中的?后面參數(shù)可以用@RequestParam。

  • form-data、x-www-form-urlencoded:不可以用@RequestBody;可以用@RequestParam。

  • 三、JPA注解

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

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

  • @NoRepositoryBean:一般用作父類的repository,有這個(gè)注解,spring不會(huì)去實(shí)例化該repository。

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

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

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

  • @SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name為sequence的名稱,以便使用,sequenceName為數(shù)據(jù)庫的sequence名稱,兩個(gè)名稱可以一致。

  • @Transient:表示該屬性并非一個(gè)到數(shù)據(jù)庫表的字段的映射,ORM框架將忽略該屬性。如果一個(gè)屬性并非數(shù)據(jù)庫表的字段映射,就務(wù)必將其標(biāo)示為@Transient,否則,ORM框架默認(rèn)其注解為@Basic。@Basic(fetch=FetchType.LAZY):標(biāo)記可以指定實(shí)體屬性的加載方式

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

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

  • @OneToOne、@OneToMany、@ManyToOne:對(duì)應(yīng)hibernate配置文件中的一對(duì)一,一對(duì)多,多對(duì)一。

  • 四、springMVC相關(guān)注解

    • @RequestMapping:

    @RequestMapping(“/path”)表示該控制器處理所有“/path”的UR L請(qǐng)求。RequestMapping是一個(gè)用來處理請(qǐng)求地址映射的注解,可用于類或方法上。

    用于類上,表示類中的所有響應(yīng)請(qǐng)求的方法都是以該地址作為父路徑。該注解有六個(gè)屬性:

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

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

    • value:指定請(qǐng)求的實(shí)際地址,指定的地址可以是URI Template 模式

    • method:指定請(qǐng)求的method類型, GET、POST、PUT、DELETE等

    • consumes:指定處理請(qǐng)求的提交內(nèi)容類型(Content-Type),如application/json,text/html;

    • produces:指定返回的內(nèi)容類型,僅當(dāng)request請(qǐng)求頭中的(Accept)類型中包含該指定類型才返回

    • @RequestParam:用在方法的參數(shù)前面。
    @RequestParam String a String a =request.getParameter(“a”)。
    • @PathVariable:路徑變量。
    @GetMapping("/car/{id}/owner/{username}")public Map<String,Object> getCar(@PathVariable("id") Integer id,@PathVariable("username") String name)
    • @RequestHeader :獲取請(qǐng)求頭信息
    @GetMapping("/car/{id}/owner/{username}")public Map<String,Object> getCar(@RequestHeader("User-Agent") String userAgent)
    • @ModelAttribute :用于將方法的參數(shù)或方法的返回值綁定到指定的模型屬性上,并返回給Web視圖
  • @ModelAttribute注釋void返回值的方法
  • @Controller public class HelloWorldController {@ModelAttributepublic void populateModel(@RequestParam String abc, Model model) {model.addAttribute("attributeName", abc);}@RequestMapping(value = "/helloWorld")public String helloWorld() {return "helloWorld";} }

    說明:
    這個(gè)例子,在獲得請(qǐng)求/helloWorld后,populateModel方法在helloWorld方法之前先被調(diào)用,它把請(qǐng)求參數(shù)(/helloWorld?abc=text)加入到一個(gè)名為attributeName的model屬性中,在它執(zhí)行后helloWorld被調(diào)用,返回視圖名helloWorld和model已由@ModelAttribute方法生產(chǎn)好了。

    這個(gè)例子中model屬性名稱和model屬性對(duì)象有model.addAttribute()實(shí)現(xiàn),不過前提是要在方法中加入一個(gè)Model類型的參數(shù)。

    當(dāng)URL或者post中不包含參數(shù)時(shí),會(huì)報(bào)錯(cuò),其實(shí)不需要這個(gè)方法,完全可以把請(qǐng)求的方法寫成下面的樣子,這樣缺少此參數(shù)也不會(huì)出錯(cuò):

    @RequestMapping(value = "/helloWorld") public String helloWorld(String abc) {return "helloWorld"; }
  • @ModelAttribute注釋返回具體類的方法
  • @ModelAttribute public Account addAccount(@RequestParam String number) {return accountManager.findAccount(number); }

    說明: 這種情況,model屬性的名稱沒有指定,它由返回類型隱含表示,如這個(gè)方法返回Account類型,那么這個(gè)model屬性的名稱是account。這個(gè)例子中model屬性名稱有返回對(duì)象類型隱含表示,model屬性對(duì)象的值就是方法的返回值。它無須要特定的參數(shù)。

  • @ModelAttribute(“attributeName”)注釋返回具體類的方法
  • @Controller public class HelloWorldController {@ModelAttribute("attributeName")public String addAccount(@RequestParam String abc) {return abc;}@RequestMapping(value = "/helloWorld")public String helloWorld() {return "helloWorld";} }

    說明:
    這個(gè)例子中使用@ModelAttribute注釋,并使用注解指定的attributeName屬性來指定model屬性的名稱。model屬性對(duì)象的值就是方法的返回值。它無須要特定的參數(shù)。

  • @ModelAttribute和@RequestMapping同時(shí)注釋一個(gè)方法
  • @Controller public class HelloWorldController {@RequestMapping(value = "/helloWorld.do")@ModelAttribute("attributeName")public String helloWorld() {return "hi";} }

    說明:
    這時(shí)這個(gè)方法的返回值并不是表示一個(gè)視圖名稱,而是model屬性的值,視圖名稱由RequestToViewNameTranslator根據(jù)請(qǐng)求”/helloWorld.do”轉(zhuǎn)換為邏輯視圖helloWorld。

    Model屬性名稱由@ModelAttribute(“attributeName”)指定,相當(dāng)于在request中封裝了key=attributeName,value=hi。

  • @ModelAttribute注釋一個(gè)方法的參數(shù)
    • 從model中獲取
    @Controller public class HelloWorldController {@ModelAttribute("user")public User addAccount() {return new User("jz","123");}@RequestMapping(value = "/helloWorld")public String helloWorld(@ModelAttribute("user") User user) {user.setUserName("jizhou");return "helloWorld";} }

    說明:
    在這個(gè)例子里,@ModelAttribute(“user”) User user注釋方法參數(shù),參數(shù)user的值來源于addAccount()方法中的model屬性。此時(shí)如果方法體沒有標(biāo)注@SessionAttributes(“user”),那么scope為request,如果標(biāo)注了,那么scope為session。

    • 從Form表單或URL參數(shù)中獲取(實(shí)際上,不做此注釋也能拿到user對(duì)象)
    @Controller public class HelloWorldController {@RequestMapping(value = "/helloWorld")public String helloWorld(@ModelAttribute User user) {return "helloWorld";} }
    • @MatrixVariable :矩陣變量
    • @CookieValue :獲取cookie值
    @GetMapping("/car/{id}/owner/{username}")public Map<String,Object> getCar(@CookieValue("_ga") Cookie cookie){}
    • @RequestBody :獲取post表單的請(qǐng)求體
    @PostMapping("/save")public Map postMethod(@RequestBody String content){Map<String,Object> map = new HashMap<>();map.put("content",content);return map;}

    五、全局異常處理

    @ControllerAdvice:包含@Component??梢员粧呙璧?。統(tǒng)一處理異常。

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

    六、項(xiàng)目中具體配置解析和使用環(huán)境

    @MappedSuperclass:

  • @MappedSuperclass 注解使用在父類上面,是用來標(biāo)識(shí)父類的

  • @MappedSuperclass 標(biāo)識(shí)的類表示其不能映射到數(shù)據(jù)庫表,因?yàn)槠洳皇且粋€(gè)完整的實(shí)體類,但是它所擁有的屬性能夠映射在其子類對(duì)用的數(shù)據(jù)庫表中

  • @MappedSuperclass 標(biāo)識(shí)的類不能再有@Entity或@Table注解

  • @Column:

  • 當(dāng)實(shí)體的屬性與其映射的數(shù)據(jù)庫表的列不同名時(shí)需要使用@Column標(biāo)注說明,該屬性通常置于實(shí)體的屬性聲明語句之前,還可與 @Id 標(biāo)注一起使用。

  • @Column 標(biāo)注的常用屬性是name,用于設(shè)置映射數(shù)據(jù)庫表的列名。此外,該標(biāo)注還包含其它多個(gè)屬性,如:unique、nullable、length、precision等。具體如下:

    • name屬性:name屬性定義了被標(biāo)注字段在數(shù)據(jù)庫表中所對(duì)應(yīng)字段的名稱

    • unique屬性:unique屬性表示該字段是否為唯一標(biāo)識(shí),默認(rèn)為false,如果表中有一個(gè)字段需要唯一標(biāo)識(shí),則既可以使用該標(biāo)記,也可以使用@Table注解中的@UniqueConstraint

    • nullable屬性:nullable屬性表示該字段是否可以為null值,默認(rèn)為true

    • insertable屬性:insertable屬性表示在使用”INSERT”語句插入數(shù)據(jù)時(shí),是否需要插入該字段的值

    • updateable屬性:updateable屬性表示在使用”UPDATE”語句插入數(shù)據(jù)時(shí),是否需要更新該字段的值

    • insertable和updateable屬性:一般多用于只讀的屬性,例如主鍵和外鍵等,這些字段通常是自動(dòng)生成的

    • columnDefinition屬性:columnDefinition屬性表示創(chuàng)建表時(shí),該字段創(chuàng)建的SQL語句,一般用于通過Entity生成表定義時(shí)使用,如果數(shù)據(jù)庫中表已經(jīng)建好,該屬性沒有必要使用

    • table屬性:table屬性定義了包含當(dāng)前字段的表名

    • length屬性:length屬性表示字段的長(zhǎng)度,當(dāng)字段的類型為varchar時(shí),該屬性才有效,默認(rèn)為255個(gè)字符

    • precision屬性和scale屬性:precision屬性和scale屬性一起表示精度,當(dāng)字段類型為double時(shí),precision表示數(shù)值的總長(zhǎng)度,scale表示小數(shù)點(diǎn)所占的位數(shù)

    總結(jié)

    以上是生活随笔為你收集整理的SpringBoot注解大全的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。